Ruby: how to check if variable exists within a hash definition

别来无恙 提交于 2019-12-24 04:04:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!