I have a OpenStruct
hash like this:
#<OpenStruct object1={
"param1"=>"2",
"param2"=>"1"
},
object2={
"param1"=>"2",
"param2"=>"1"
},
object3={
"param1"=>"2",
"param2"=>"1"
}...
How can I use each
on this?
What is a Struct in Ruby? A struct is a built-in Ruby class, it's used to create new classes which produce value objects. A value object is used to store related attributes together.
An OpenStruct is a data structure, similar to a Hash , that allows the definition of arbitrary attributes with their accompanying values. This is accomplished by using Ruby's metaprogramming to define methods on the class itself.
OpenStruct has a method called marshal_dump that returns the underlying hash structure:
your_open_struct.marshal_dump.each{ |k,v| puts "#{k} => #{v}" }
If you are using Ruby 2.0, you can use also to_h like so:
your_open_struct.to_h.each{ |k,v| puts "#{k} => #{v}" }
Unlike marshal_dump
, which returns the actual hash structure, to_h
returns a hash with all the keys converted to symbols for easier access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With