Typically, we define a hash as
h={:a=>val1, :b=>val2}
However, i want to add a condition to only add in the key :b if val2 is not a nil value. Something like
h={:a=>val1}
h[:b]=val2 if val2
But can it be encapsulated in a single line?
Typically, we define a hash as
h={:a=>val1, :b=>val2}
However, i want to add a condition to only add in the key :b if val2 is not a nil value. Something like
h={:a=>val1}
h[:b]=val2 if val2
But can it be encapsulated in a single line?
You could override the []= operator for just that one hash, or make a subclass of Hash and override it there.
hash = {}
class << hash
def []=(key, value)
case key
when :b
raise StandardError("Invalid :b value") if value.nil?
end
super(key,value)
end
end
hash[:a] = 10
hash[:b] = nil # Will raise exception
h = { :a => val1 }.merge(val2 ? { :b => val2 } : {})
But don't do this. Just keep it simple.
You don't have to worry about nil elements in hash, because you can simply clean up hash from them:
{:a => 1, :b => nil}.reject { |k, v| v.nil? } # {:a => 1}