假设我有一个w_data
哈希
{"latitude"=>"40.695", "air_temperature"=>"-10", "longitude"=>"-96.854", "datetime"=>"2014-01-01 02:55:00"}
我希望w_data.latitude
而不是w_data["latitude"]
怎么做?
答案 0 :(得分:8)
我要说不使用OpenStruct,因为它nukes the method cache every time you create a new one。
相反,考虑像hashie-mash这样的宝石,或者滚动你自己的类似哈希:
Hashie::Mash
:
hsh = Hashie::Mash.new("latitude"=>"40.695", "air_temperature"=>"-10", "longitude"=>"-96.854", "datetime"=>"2014-01-01 02:55:00")
hsh.latitude
=> "40.695"
自定义解决方案:
class AccessorHash < Hash
def method_missing(method, *args)
s_method = method.to_s
if s_method.match(/=$/) && args.length == 1
self[s_method.chomp("=")] = args[0]
elsif args.empty? && key?(s_method)
self.fetch(s_method)
elsif args.empty? && key?(method)
self.fetch(method)
else
super
end
end
end
hsh = AccessorHash.new("latitude"=>"40.695", "air_temperature"=>"-10", "longitude"=>"-96.854", "datetime"=>"2014-01-01 02:55:00")
hsh.latitude # => "40.695"
hsh.air_temperature = "16"
hsh => # {"latitude"=>"40.695", "air_temperature"=>"16", "longitude"=>"-96.854", "datetime"=>"2014-01-01 02:55:00"}
答案 1 :(得分:4)
如果你想要一个纯Ruby解决方案,只需打开Hash类并升级method_missing
方法!
class Hash
def method_missing method_name, *args, &block
return self[method_name] if has_key?(method_name)
return self[$1.to_sym] = args[0] if method_name.to_s =~ /^(.*)=$/
super
end
end
现在,每个哈希都有这种能力。
hash = {:five => 5, :ten => 10}
hash[:five] #=> 5
hash.five #=> 5
hash.fifteen = 15
hash[:fifteen] #=> 15
hash.fifteen #=> 15
method_missing
在每个Ruby类中都可用,以捕获对尚未存在的方法的尝试调用。我已将此转变为博客文章(带有交互式Codewars kata):
答案 2 :(得分:2)
将哈希转换为OpenStruct。这里:
require 'ostruct'
w_data = OpenStruct.new
hash = {"latitude"=>"40.695", "air_temperature"=>"-10", "longitude"=>"-96.854", "datetime"=>"2014-01-01 02:55:00"}
w_data.marshal_load(hash)
w_data.longitude
#=> "-96.854"
另一种更简单的方法:
require 'ostruct'
hash = {"latitude"=>"40.695", "air_temperature"=>"-10", "longitude"=>"-96.854", "datetime"=>"2014-01-01 02:55:00"}
w_data = OpenStruct.new(hash)
w_data.longitude
#=> "-96.854"