Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

hashtable

ruby

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.

like image 431
danh Avatar asked Jan 05 '13 20:01

danh


People also ask

How can you tell if a key is present in a hash?

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.

What is a key value hash?

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.


1 Answers

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
like image 64
sawa Avatar answered Oct 27 '22 00:10

sawa