eibersji
eibersji

Reputation: 1216

Can't access Hash values

I have this code:

price = variant[merchant["variant_code"]]

which translates to this: variant["PRDCT-A"] but my problem is that it returns nil because my variant hash looks like this: {:"PRDCT-A"=>{:price=>1495.0}} it has : but I am passing just "PRDCT-A" which should be :"PRDCT-A".

I have tried concat but it does not work, how can I include the colon so I can access the hash values?

Upvotes: 2

Views: 567

Answers (3)

Ashok Damaniya
Ashok Damaniya

Reputation: 303

if i am not wrong your hash structure might be like

merchant = {variant_code: 'PRDCT-A'}
variant = {:"PRDCT-A"=>{:price=>1495.0}}

and you want to access variants value with help of merchant hash

you should try this,

variant.dig(merchant[:variant_code].to_sym)

Upvotes: 3

Girish Bhanarkar
Girish Bhanarkar

Reputation: 93

You can simply convert to json and use it.

variant = variant.as_json

variant['PRDCT-A']

Upvotes: -1

fidato
fidato

Reputation: 719

Please try with_indifferent_access with variant hash like follow -

variant = variant.with_indifferent_access

And access again using same statement. i.e.

price = variant[merchant["variant_code"]]

I hope this helps.

Upvotes: 1

Related Questions