Home add key in hash based on condition
Reply: 2

add key in hash based on condition

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

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 Reply to 2018-01-05 17:58:48Z
@customer_info[:c] = something if customer
jvillian Reply to 2018-01-05 18:57:50Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.302345 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO