4

Typically when an element is passed into a hash with no matching key, the hash returns nil.

hsh = {1 => "one", 2 => "two"}
hsh[3] #=> nil

I want to form a hash that returns the value passed into it if there is no match.

hsh[3] #=> 3

I'm guessing that a solution for this might involve a lambda of some kind...?

** Right now I'm using a clumsy solution for this that uses a conditional method to prevent non-matching keys from being passed into the hash..

4

2 回答 2

8

如果您只想返回新值但不添加它们:

 h = Hash.new { |_hash, key| key }

要最初填充此哈希,您可以执行以下操作:

 h.merge( {1 => "one", 2 => "two"} )

如果哈希已经创建*:

 h.default_­proc = proc do |_hash,key|
     key
 end

#h[3]
#=> 3

*仅在 ruby​​ 1.9 及更高版本中

于 2013-08-26T17:22:31.653 回答
1

尝试这个:

hsh.default_proc = proc do |hash, key|
  hash[key] = key
end

只返回密钥,这是一个微不足道的改变:

hsh.default_proc = proc do |hash, key|
  key
end
于 2013-08-26T17:12:33.983 回答