Is there anything like this possible in Ruby:
hash = { :foo => 'bar', :bar => lambda{ condition ? 开发者_Python百科return 'value1' : return 'value2'}}
That actual code doesn't work (clearly), and I know I could just do the logic before the hash assignment, but it would be nice to work inside the assignment like this. Is such a thing possible?
You don't need a lambda for that, just this should work:
hash = {
:foo => 'bar',
:bar => condition ? 'value1' : 'value2'
}
Or if you want to use a function result on hash,
hash= {
:foo=> 'foooooo',
:bar=> lambda {
if condition
value1
else
value2
end
}.call
}
精彩评论