Skip to content
Tags

, ,

Convert hash to object

March 15, 2013

I wanted to quickly convert a hash into an object with attributes the same as the keys of the hash. OpenStruct to the rescue

http://ruby-doc.org/stdlib-2.0/libdoc/ostruct/rdoc/OpenStruct.html

1.9.3p194 :024 > obj = OpenStruct.new({:color => ‘red’, :weight => 3 })
=> #<OpenStruct color=”red”, weight=3>
1.9.3p194 :025 > obj.color
=> “red”
1.9.3p194 :026 > obj.weight
=> 3

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: