Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get JavaScript style hash access?

Tags:

object

ruby

hash

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.

I am using ruby 1.9.2

Update:

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.

like image 949
Nick Vanderbilt Avatar asked Jan 19 '12 22:01

Nick Vanderbilt


2 Answers

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
like image 193
DigitalRoss Avatar answered Nov 17 '22 03:11

DigitalRoss


You are looking for OpenStruct

$ require 'ostruct'
$ large_hash_obj = OpenStruct.new large_hash
$ large_hash_obj.boy
=> "John"
like image 7
iwasrobbed Avatar answered Nov 17 '22 01:11

iwasrobbed