Is there a nice (one line) way of writing a hash in ruby with some entry only there if a condition is fulfilled? I thought of
{:a => 'a', :b => ('b' if condition)}
But that leaves :b == nil if the condition is not fulfilled. I realize this could be done easily in two lines or so, but it would be much nicer in one line (e.g. when passing the hash to a function).
Am I missing (yet) another one of ruby’s amazing features here? 😉
UPDATE Ruby 2.4+
Since ruby 2.4.0, you can use the compact method:
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:
yields, for cond == true:
and for cond == false
UPDATE for ruby 1.9.3
This is equivalent – a bit more concise and in ruby 1.9.3 notation: