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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 01:27:28

问题


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

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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/14175958/conditional-inclusion-of-a-key-value-pair-in-a-hash

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