Conditional inclusion of a key-value pair in a hash [closed]

时光总嘲笑我的痴心妄想 提交于 2019-12-05 02:14:24
sawa
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

I don't really like it but this is pretty terse (and confusing)

def self.some_hash(some_key=nil)
  Hash[[["foo", "bar"], [some_key, "some value"]].select(&:first)]
end

This may be a little better.

def self.some_hash(some_key=nil)
  {"foo" => "bar", some_key => "some_value"}.keep_if{ |k, _| k }
end

Hash#keep_if

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!