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.
We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With