meow
meow

Reputation: 28164

Adding a key only to a hash based on an if statement

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?

Upvotes: 3

Views: 6183

Answers (5)

schpet
schpet

Reputation: 10620

as of ruby 2.4, you can use Hash#compact

h = { a: 1, b: false, c: nil }
h.compact     #=> { a: 1, b: false }
h             #=> { a: 1, b: false, c: nil }

Upvotes: 2

lest
lest

Reputation: 8100

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}

Upvotes: 4

guns
guns

Reputation: 10805

h = { :a => val1 }.merge(val2 ? { :b => val2 } : {})

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

Upvotes: 5

AboutRuby
AboutRuby

Reputation: 8116

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

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124632

h[:b] = val unless val.nil?

Upvotes: 4

Related Questions