简体   繁体   English

无法访问哈希值

[英]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" . 转换为: variant["PRDCT-A"]但是我的问题是它返回nil因为我的variant哈希看起来像这样: {:"PRDCT-A"=>{:price=>1495.0}}它具有:我只通过了"PRDCT-A" ,它应该是:"PRDCT-A"

I have tried concat but it does not work, how can I include the colon so I can access the hash values? 我已经尝试过concat但它不起作用,如何包含冒号以便可以访问哈希值?

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)

Please try with_indifferent_access with variant hash like follow - 请尝试使用with_indifferent_accessvariant哈希,如下所示-

variant = variant.with_indifferent_access

And access again using same statement. 并使用相同的语句再次访问。 ie

price = variant[merchant["variant_code"]]

I hope this helps. 我希望这有帮助。

You can simply convert to json and use it. 您可以简单地转换为json并使用它。

variant = variant.as_json

variant['PRDCT-A']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM