How can I get JavaScript style hash access?

后端 未结 4 1762
余生分开走
余生分开走 2021-02-19 11:05

I am aware of this feature provided by ActiveSupport.

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


        
4条回答
  •  执笔经年
    2021-02-19 11:38

    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
    

提交回复
热议问题