哈希['关键']用Ruby hash.key [英] hash['key'] to hash.key in Ruby
本文介绍了哈希['关键']用Ruby hash.key的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个哈希
富= {'酒吧'=>'巴兹'}
我想调用 foo.bar#=> 巴兹
我的动机是重写一个ActiveRecord查询到原始SQL查询(使用型号的find_by_sql)。此方法返回的SELECT子句值作为密钥的哈希值。但是,我现有的code依赖的object.method点符号。我想要做的最小的code重写。谢谢你。
编辑:看来lua有这样的特征:
点= {X = 10,Y = 20} - 创建新表
打印(点[X]) - 打印10
打印(point.x) - 具有完全相同的上述含义线
解决方案
>>需要'ostruct
=> []
>>富= {'酒吧'=>'巴兹'}
=> {栏=>中巴兹}
>> foo_obj = OpenStruct.new FOO
=> #< OpenStruct栏=巴兹>
>> foo_obj.bar
=> 巴兹
>>
I have a a hash
foo = {'bar'=>'baz'}
I would like to call foo.bar #=> 'baz'
My motivation is rewriting an activerecord query into a raw sql query (using Model#find_by_sql). This returns a hash with the SELECT clause values as keys. However, my existing code relies on object.method dot notation. I'd like to do minimal code rewrite. Thanks.
Edit: it appears Lua has this feature:
point = { x = 10, y = 20 } -- Create new table
print(point["x"]) -- Prints 10
print(point.x) -- Has exactly the same meaning as line above
解决方案
>> require 'ostruct'
=> []
>> foo = {'bar'=>'baz'}
=> {"bar"=>"baz"}
>> foo_obj = OpenStruct.new foo
=> #<OpenStruct bar="baz">
>> foo_obj.bar
=> "baz"
>>
这篇关于哈希['关键']用Ruby hash.key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文