在哈希中有条件地包含键值对 [英] Conditional inclusion of a key-value pair in a hash

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

问题描述

有人可以帮助我缩短以下方法吗?我从这个开始,我很喜欢它:

Can someone help me shorten the following method? I began with this, which I liked just fine:

def self.some_hash
  { "foo" => "bar" }
end

现在,我想添加一个可选键.我能想到的最简洁的语法是:

Now I want to add an optional key. The tersest syntax I can think of is this:

def self.some_hash(some_key=nil)
  answer = { "foo" => "bar" }
  answer[some_key] = "yucky, long-winded syntax" if some_key
  answer
end

修改后的方法有效,但是我对虚拟墨水的浪费不满意.有什么办法可以缩短它?我意识到可以在哈希字面量上使用三元运算符,但这会(在我看来)在条件的每个分支上强制重复"foo" => "bar"对,这也比原始数据要少.

The modified method works, but I'm dissatisfied with waste of virtual ink. Is there a way to shorten it? I realize one could employ a ternary operator on the hash literal, but that would force (I think) the repetition the "foo" => "bar" pair on each branch of the condition, which is also slightly less than pristine.

推荐答案

def self.some_hash(some_key = nil)
  {"foo" => "bar"}.merge(some_key ? {some_key => "yucky, long-winded syntax"} : {})
end

或者,如果修改原始哈希,

Or, if modifying the original hash,

def self.some_hash(some_key = nil)
  {"foo" => "bar"}
  .tap{|h| h.merge!(some_key => "yucky, long-winded syntax") if some_key}
end

或者,也许您可​​以按照接近原始版本的方式进行操作:

Or, maybe you can do it in a way close to your original:

def self.some_hash(some_key = nil)
  {"foo" => "bar"}
  .tap{|h| h[some_key] = "yucky, long-winded syntax" if some_key}
end

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

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