Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning struct data as a hash in ruby

Tags:

Is there a valid reason for there not being a method to return the data of a standard ruby struct as a hash (member, value pairs)? Seeing that structs and hashes have very similar use cases, I'm surprised that no such method exists. Or does it, and I'm just too blind?

It's easy to implement (and i have done so for now), but lack of such functionality in the standard libs, has me thinking that I might have not really grasped the concept of structs in ruby.

like image 334
cvshepherd Avatar asked Nov 10 '11 16:11

cvshepherd


People also ask

How do you create a Hash object in Ruby?

In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.

How do you add a value to a Hash in Ruby?

Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.

How do you traverse a Hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.

What is a Hash in Ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.


Video Answer


1 Answers

(Ruby <= 1.9.3) OpenStruct has OpenStruct#marshall_dump and Struct has Struct#each_pair (use to_a to get the pairs and Hash+to_a to get the hash):

Person = Struct.new(:name, :age) person = Person.new("Jamie", 23) person_hash = Hash[person.each_pair.to_a] #=> {:age=>23, :name=>"Jamie"} 

With Ruby 2.0 things are easier: Struct#to_h, OpenStruct#to_h:

Person = Struct.new(:name, :age) person = Person.new("Jamie", 23) person_hash = person.to_h #=> {:age=>23, :name=>"Jamie"} 
like image 150
tokland Avatar answered Oct 25 '22 02:10

tokland