Conditional key/value in a ruby hash

UPDATE Ruby 2.4+

Since ruby 2.4.0, you can use the compact method:

{ a: 'a', b: ('b' if cond) }.compact

Original answer (Ruby 1.9.2)

You could first create the hash with key => nil for when the condition is not met, and then delete those pairs where the value is nil. For example:

{ :a => 'a', :b => ('b' if cond) }.delete_if{ |k,v| v.nil? }

yields, for cond == true:

{:b=>"b", :a=>"a"}

and for cond == false

{:a=>"a"} 

UPDATE for ruby 1.9.3

This is equivalent – a bit more concise and in ruby 1.9.3 notation:

{ a: 'a', b: ('b' if cond) }.reject{ |k,v| v.nil? }

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)