ruby 哈希中的条件键/值 [英] Conditional key/value in a ruby hash

查看:41
本文介绍了ruby 哈希中的条件键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种不错的(一行)方法可以在 ruby​​ 中写入一个只有在满足条件时才会出现的条目的散列?我想到了

Is there a nice (one line) way of writing a hash in ruby with some entry only there if a condition is fulfilled? I thought of

{:a => 'a', :b => ('b' if condition)}

但是如果条件不满足,那就剩下 :b == nil.我意识到这可以在两行左右轻松完成,但在一行中会更好(例如,将哈希传递给函数时).

But that leaves :b == nil if the condition is not fulfilled. I realize this could be done easily in two lines or so, but it would be much nicer in one line (e.g. when passing the hash to a function).

我是否(还)错过了 ruby​​ 的另一个惊人功能?;)

Am I missing (yet) another one of ruby's amazing features here? ;)

推荐答案

当条件不满足时,您可以先用 key => nil 创建散列,然后删除那些值为 nil 的对.例如:

You could first create the hash with key => nil for when the condition is not met, and then delete those pairs where the value is nil. For example:

{ :a => 'a', :b => ('b' if cond) }.delete_if{ |k,v| v.nil? }

产量,对于 cond == true:

yields, for cond == true:

{:b=>"b", :a=>"a"}

对于 cond == false

and for cond == false

{:a=>"a"} 

更新

这是等效的 - 更简洁一点,使用 ruby​​ 1.9.3 表示法:

This is equivalent - a bit more concise and in ruby 1.9.3 notation:

{ a: 'a', b: ('b' if cond) }.reject{ |k,v| v.nil? }

更新 Ruby 2.4+

从 ruby​​ 2.4.0 开始,您可以使用 compact 方法:

Since ruby 2.4.0, you can use the compact method:

{ a: 'a', b: ('b' if cond) }.compact

这篇关于ruby 哈希中的条件键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆