问题
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