Home add key in hash based on condition

# add key in hash based on condition

User7354632781
1#
User7354632781 Published in 2018-01-05 17:55:12Z
 I have following method def some_method ...do something here... @customer_info = { a: a, b: b } end  I want to add key c in @customer_info if variable customer is true so something like, @customer_info = { a: a, b: b, c: something if customer is true }  tried to do something like this but no luck @customer_info.merge(customer.present? {c: something} : {}) 
steenslag
2#
 @customer_info[:c] = something if customer 
 Perhaps you are simply missing ? in your ternary operator? Your approach seems to work for me in console: > customer_info = {a: :a, b: :b} => {:a=>:a, :b=>:b} > c = false => false > customer_info.merge(c ? {c: c} : {}) => {:a=>:a, :b=>:b} > c = true => true > customer_info.merge(c ? {c: c} : {}) => {:a=>:a, :b=>:b, :c=>true}  So, this: @customer_info.merge(customer.present? {c: something} : {})  Should be more like: @customer_info.merge(customer.present? ? {c: something} : {})  Quick Update As pointed out in the comments, this should be more like: @customer_info.merge!({c: something}) if customer.present?  The commentators do a nice job of explaining why.