39

Given I have this hash:

 h = { a: 'a', b: 'b', c: { d: 'd', e: 'e'} }

And I convert to OpenStruct:

o = OpenStruct.new(h)
 => #<OpenStruct a="a", b="b", c={:d=>"d", :e=>"e"}> 
o.a
 => "a" 
o.b
 => "b" 
o.c
 => {:d=>"d", :e=>"e"} 
2.1.2 :006 > o.c.d
NoMethodError: undefined method `d' for {:d=>"d", :e=>"e"}:Hash

I want all the nested keys to be methods as well. So I can access d as such:

o.c.d
=> "d"

How can I achieve this?

4

9 Answers 9

55

You can monkey-patch the Hash class

class Hash
  def to_o
    JSON.parse to_json, object_class: OpenStruct
  end
end

then you can say

h = { a: 'a', b: 'b', c: { d: 'd', e: 'e'} }
o = h.to_o
o.c.d # => 'd'

See Convert a complex nested hash to an object.

4
  • 8
    Been using Ruby for over 10 years and I'm still surprised by its elegance. Commented Jan 24, 2018 at 19:54
  • 2
    Though it should work to solve the problem, but this process has some side-effects like it will change the default Hash behavior in all places in the project, which might create unforeseen issues in coming days. So I would rather go with max_pleaner or Donato JSON.parse(h.to_json, object_class: OpenStruct)which seems to solve the issue in place without side-effects. Commented Mar 1, 2018 at 11:39
  • 2
    FYI this only works with simple values. I had issues when I applied this approach to more complex objects (e.g. BigDecimal or custom ActiveRecord objects) Commented Mar 4, 2018 at 19:30
  • yes it changes values of symbol to string
    – Piioo
    Commented Jun 16, 2023 at 7:35
35

I came up with this solution:

h = { a: 'a', b: 'b', c: { d: 'd', e: 'e'} }
json = h.to_json
=> "{\"a\":\"a\",\"b\":\"b\",\"c\":{\"d\":\"d\",\"e\":\"e\"}}" 
object = JSON.parse(json, object_class:OpenStruct)
object.c.d
 => "d" 

So for this to work, I had to do an extra step: convert it to json.

5
  • Messy, but functional. There's better ways though.
    – tadman
    Commented Feb 28, 2017 at 22:38
  • 1
    Dependencies? Openstruct and Json are part of the standard library.
    – Mikey T.K.
    Commented Mar 30, 2018 at 5:42
  • Nice, this seems to work well. One difference I encountered is I had to call object.table.c.d. Commented Jul 25, 2018 at 13:57
  • 1
    I believe generating json just to parse it is not very efficient approach Commented Aug 2, 2021 at 9:40
  • when a value is a symbol, it converts it to a string
    – Piioo
    Commented Jun 16, 2023 at 7:33
30

personally I use the recursive-open-struct gem - it's then as simple as RecursiveOpenStruct.new(<nested_hash>)

But for the sake of recursion practice, I'll show you a fresh solution:

require 'ostruct'

def to_recursive_ostruct(hash)
  result = hash.each_with_object({}) do |(key, val), memo|
    memo[key] = val.is_a?(Hash) ? to_recursive_ostruct(val) : val
  end
  OpenStruct.new(result)
end

puts to_recursive_ostruct(a: { b: 1}).a.b
# => 1

edit

Weihang Jian showed a slight improvement to this here https://stackoverflow.com/a/69311716/2981429

def to_recursive_ostruct(hash)
  hash.each_with_object(OpenStruct.new) do |(key, val), memo|
    memo[key] = val.is_a?(Hash) ? to_recursive_ostruct(val) : val
  end
end

Also see https://stackoverflow.com/a/63264908/2981429 which shows how to handle arrays

note

the reason this is better than the JSON-based solutions is because you can lose some data when you convert to JSON. For example if you convert a Time object to JSON and then parse it, it will be a string. There are many other examples of this:

class Foo; end
JSON.parse({obj: Foo.new}.to_json)["obj"]
# => "#<Foo:0x00007fc8720198b0>"

yeah ... not super useful. You've completely lost your reference to the actual instance.

8
  • 1
    i used your answer and works well with hash, what about if having array value with hash inside e.g. { a: 'a', b: 'b', c: [{ d: 'd', e: 'e'}] }, so I can do c.d => 'd' Thanks :)
    – aldrien.h
    Commented Aug 24, 2018 at 6:42
  • @aldrien.h If you had {c: [{d: 'd'}]} why would you want to use c.d? How would that work if you had multiple hashes in the array? Commented Nov 27, 2018 at 18:23
  • 1
    The JSON.parse answer is far more flexible and elegant.
    – Tonči D.
    Commented Jan 11, 2019 at 13:16
  • 1
    @TončiD. it's really not. The problem is that not everything can be converted to JSON and keep its same Ruby class. For example JSON.parse({now: Time.now}.to_json)["now"].class == String ... The Time.now is no longer a Time object when you parse/unparse it. Commented Jan 11, 2019 at 21:28
  • 1
    @maxpleaner adding this line below memo[key] = ... would take care of arrays: memo[key] = val.map { |v| v.is_a?(Hash) ? to_recursive_ostruct(v) : v } if val.is_a?(Array)
    – Medardas
    Commented Feb 29, 2020 at 10:20
9

Here's a recursive solution that avoids converting the hash to json:

def to_o(obj)
  if obj.is_a?(Hash)
    return OpenStruct.new(obj.map{ |key, val| [ key, to_o(val) ] }.to_h)
  elsif obj.is_a?(Array)
    return obj.map{ |o| to_o(o) }
  else # Assumed to be a primitive value
    return obj
  end
end
2
  • as each_with_object is deprecated, for me this is the best solution Commented Aug 30, 2020 at 17:43
  • 1
    @ChristianoMatos Can you give some references about the deprecation? I don't see any evidence. Commented Sep 24, 2021 at 7:57
4

My solution, based on max pleaner's answer and similar to Xavi's answer:

require 'ostruct'

def initialize_open_struct_deeply(value)
  case value
  when Hash
    OpenStruct.new(value.transform_values { |hash_value| send __method__, hash_value })
  when Array
    value.map { |element| send __method__, element }
  else
    value
  end
end
3

My solution is cleaner and faster than @max-pleaner's.

I don't actually know why but I don't instance extra Hash objects:

def dot_access(hash)
  hash.each_with_object(OpenStruct.new) do |(key, value), struct|
    struct[key] = value.is_a?(Hash) ? dot_access(value) : value
  end
end

Here is the benchmark for you reference:

require 'ostruct'

def dot_access(hash)
  hash.each_with_object(OpenStruct.new) do |(key, value), struct|
    struct[key] = value.is_a?(Hash) ? dot_access(value) : value
  end
end

def to_recursive_ostruct(hash)
  result = hash.each_with_object({}) do |(key, val), memo|
    memo[key] = val.is_a?(Hash) ? to_recursive_ostruct(val) : val
  end
  OpenStruct.new(result)
end

require 'benchmark/ips'
Benchmark.ips do |x|
  hash = { a: 1, b: 2, c: { d: 3 } }
  x.report('dot_access') { dot_access(hash) }
  x.report('to_recursive_ostruct') { to_recursive_ostruct(hash) }
end
Warming up --------------------------------------
          dot_access     4.843k i/100ms
to_recursive_ostruct     5.218k i/100ms
Calculating -------------------------------------
          dot_access     51.976k (± 5.0%) i/s -    261.522k in   5.044482s
to_recursive_ostruct     50.122k (± 4.6%) i/s -    250.464k in   5.008116s
0

Here is one way to override the initializer so you can do OpenStruct.new({ a: "b", c: { d: "e", f: ["g", "h", "i"] }}).

Further, this class is included when you require 'json', so be sure to do this patch after the require.

class OpenStruct
  def initialize(hash = nil)
    @table = {}
    if hash
      hash.each_pair do |k, v|
        self[k] = v.is_a?(Hash) ? OpenStruct.new(v) : v
      end
    end
  end

  def keys
    @table.keys.map{|k| k.to_s}
  end
end
0

Basing a conversion on OpenStruct works fine until it doesn't. For instance, none of the other answers here properly handle these simple hashes:

people = { person1: { display: { first: 'John' } } }
creds = { oauth: { trust: true }, basic: { trust: false } }

The method below works with those hashes, modifying the input hash rather than returning a new object.

def add_indifferent_access!(hash)
  hash.each_pair do |k, v|
    hash.instance_variable_set("@#{k}", v.tap { |v| send(__method__, v) if v.is_a?(Hash) } )
    hash.define_singleton_method(k, proc { hash.instance_variable_get("@#{k}") } )
  end
end

then

add_indifferent_access!(people)
people.person1.display.first # => 'John'

Or if your context calls for a more inline call structure:

creds.yield_self(&method(:add_indifferent_access!)).oauth.trust # => true

Alternatively, you could mix it in:

module HashExtension
  def very_indifferent_access!
    each_pair do |k, v|
      instance_variable_set("@#{k}", v.tap { |v| v.extend(HashExtension) && v.send(__method__) if v.is_a?(Hash) } )
      define_singleton_method(k, proc { self.instance_variable_get("@#{k}") } )
    end
  end
end

and apply to individual hashes:

favs = { song1: { title: 'John and Marsha', author: 'Stan Freberg' } }
favs.extend(HashExtension).very_indifferent_access!
favs.song1.title

Here is a variation for monkey-patching Hash, should you opt to do so:

class Hash
  def with_very_indifferent_access!
    each_pair do |k, v|
      instance_variable_set("@#{k}", v.tap { |v| v.send(__method__) if v.is_a?(Hash) } )
      define_singleton_method(k, proc { instance_variable_get("@#{k}") } )
    end
  end
end
# Note the omission of "v.extend(HashExtension)" vs. the mix-in variation.

Comments to other answers expressed a desire to retain class types. This solution accommodates that.

people = { person1: { created_at: Time.now } }
people.with_very_indifferent_access!
people.person1.created_at.class # => Time

Whatever solution you choose, I recommend testing with this hash:

people = { person1: { display: { first: 'John' } }, person2: { display: { last: 'Jingleheimer' } } }

0

If you are ok with monkey-patching the Hash class, you can do:

require 'ostruct'

module Structurizable
  def each_pair(&block)
    each do |k, v|
      v = OpenStruct.new(v) if v.is_a? Hash

      yield k, v
    end
  end
end

Hash.prepend Structurizable

people = { person1: { display: { first: 'John' } }, person2: { display: { last: 'Jingleheimer' } } }

puts OpenStruct.new(people).person1.display.first

Ideally, instead of pretending this, we should be able to use a Refinement, but for some reason I can't understand it didn't worked for the each_pair method (also, unfortunately Refinements are still pretty limited)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.