开发者

Anonymous method inside hash assignment

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜