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.
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.
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.
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.
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.
(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"}
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