本文介绍了如何获得JavaScript样式哈希访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道ActiveSupport提供的此功能.

I am aware of this feature provided by ActiveSupport.

h = ActiveSupport::OrderedOptions.new
h.boy = 'John'
h.girl = 'Mary'
h.boy  # => 'John'
h.girl # => 'Mary'

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

However I already have a large hash and I want to access that hash using dot notation. This is what I tried:

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

那没有用.我该如何进行这项工作.

That did not work. How can I make this work.

我正在使用ruby 1.9.2

I am using ruby 1.9.2

更新:

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

Sorry I should have mentioned that I can't use openstruct because it does not have each_pair method which Struct has. I do not know keys beforehand so I can't use openstruct.

推荐答案

OpenStruct 应该可以很好地工作.

OpenStruct should work nicely for this.

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

If you want to see how it works, or perhaps make a customized version, start with something like this:

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

这篇关于如何获得JavaScript样式哈希访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:35