Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use "each" on an Openstruct object?

Tags:

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?

like image 649
Dodjs Avatar asked Dec 31 '11 09:12

Dodjs


People also ask

Does Ruby have struct?

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.

What is OpenStruct Ruby?

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.


1 Answers

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.

like image 94
Ben Lee Avatar answered Oct 27 '22 05:10

Ben Lee