问题
I'm new to Ruby. Is there a way to do the following?
hash = {
:key1 => defined? value1 ? value1 : nil,
:key2 => defined? value2 ? value2 : nil
}
puts hash[:key1] # outputs: ["expression"]
The above code stores the expression, instead of the value (if it is defined) or nil (if it is not defined).
回答1:
You're looking for lambda
, or Proc
.
hash = {
:key1 => lambda { defined?(value1) ? value1 : nil },
:key2 => lambda { defined?(value2) ? value1 : nil }
}
hash[:key1].call
http://www.ruby-doc.org/core-1.9.2/Kernel.html#method-i-lambda
回答2:
d11wtg answer will do. Also, by adding parentheses, the values are stored as expected:
hash = {
:key1 => (defined? value1) ? value1 : nil,
:key2 => (defined? value2) ? value2 : nil
}
回答3:
What exactly do you want to do?
hash[:key].nil?
will return true or false, depending if the key exists. Not sure if that's what you are looking for.
来源:https://stackoverflow.com/questions/7903656/ruby-how-to-check-if-variable-exists-within-a-hash-definition