views:

66

answers:

4

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?

+2  A: 
h[:b] = val unless val.nil?
Ed Swangren
This is no different than the original...
mathepic
I guess my point was that it is stupid to worry about doing it in a single line. Who cares? Worry about real problems.
Ed Swangren
point taken! thanks for the note
ming yeow
+1  A: 

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
AboutRuby
this is too complex for now, but would be great for future projects with such a need , thanks!
ming yeow
+2  A: 
h = { :a => val1 }.merge(val2 ? { :b => val2 } : {})

But don't do this. Just keep it simple.

guns
+1  A: 

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}
lest
But it appears that the OP wanted [:a] in there even if its value was nil.
Carl Manaster