开发者

Anonymous method inside hash assignment

开发者 https://www.devze.com 2023-04-09 06:19 出处:网络
Is there anything like this possible in Ruby: hash = { :foo => \'bar\', :bar => lambda{ condition ? 开发者_Python百科return \'value1\' : return \'value2\'}}

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消