根据定义,当键不存在时,ruby散列返回nil。但我需要使用自定义消息来代替nil。所以我使用的是这样的东西:
val = h['key'].nil? ? "No element present" : h['key']但这有一个严重的缺点。如果键被赋值为nil,那么在这种情况下也会返回"No element present“。
有没有办法完美地做到这一点呢?
谢谢
发布于 2011-01-31 20:10:27
用这种方式初始化你的哈希:
> hash = Hash.new{|hash,key| hash[key] = "No element against #{key}"}
=> {}
> hash['a']
=> "No element against a"
> hash['a'] = 123
=> 123
> hash['a']
=> 123
> hash['b'] = nil
=> nil
> hash['b']
=> nil 希望这能有所帮助:)
发布于 2011-01-31 20:09:26
irb(main):001:0> h = Hash.new('No element present')
=> {}
irb(main):002:0> h[1]
=> "No element present"
irb(main):003:0> h[1] = nil
=> nil
irb(main):004:0> h[1]
=> nil
irb(main):005:0> h[2]
=> "No element present"发布于 2011-01-31 20:09:35
您可以改用has_key?方法
val = h.has_key?('key') ? h['key'] : "No element present"https://stackoverflow.com/questions/4850614
复制相似问题