如何获得JavaScript样式的哈希访问?

Nic*_*ilt 13 ruby hash object

我知道ActiveSupport提供的这个功能.

h = ActiveSupport::OrderedOptions.new
h.boy = 'John'
h.girl = 'Mary'
h.boy  # => 'John'
h.girl # => 'Mary'
Run Code Online (Sandbox Code Playgroud)

但是我已经有一个大哈希,我想使用点表示法访问该哈希.这是我试过的:

large_hash = {boy: 'John', girl: 'Mary'}
h = ActiveSupport::OrderedOptions.new(large_hash)
h.boy # => nil
Run Code Online (Sandbox Code Playgroud)

那没用.我怎样才能做到这一点.

我正在使用ruby 1.9.2

更新:

对不起我应该提到我不能使用openstruct,因为它没有Struct所具有的each_pair方法.我事先不知道密钥所以我不能使用openstruct.

Dig*_*oss 9

OpenStruct应该很好地为此工作.

如果您想了解它的工作原理,或者想要制作自定义版本,请从以下内容开始:

h = { 'boy' => 'John', 'girl' => 'Mary' }

class << h
  def method_missing m
    self[m.to_s]
  end
end

puts h.nothing
puts h.boy
puts h.girl
Run Code Online (Sandbox Code Playgroud)


iwa*_*bed 6

您正在寻找OpenStruct

$ require 'ostruct'
$ large_hash_obj = OpenStruct.new large_hash
$ large_hash_obj.boy
=> "John"
Run Code Online (Sandbox Code Playgroud)