To_h in Ruby 2.0
With few major changes ruby 2.0 is out today, out the many new features I really liked the to_h
We can convert a class to a Hash, using to_h:
“
# Ruby 2.0:
Student = Struct.new(:name, :age, :year) do
def info
#...
end
end
dude = Student.new('Hemanth', '16', 2)
dude.to_h # => {:name=>"Hemanth", :age=>"16", :year=>2}
nil.to_h # => {}
P.S : This has been implemented for nil, Struct and OpenStruct, but not for Enumerable/Array, so :
module Enumerable # mapping array into a hash def to_h(&block)
inject({}) {|hash, *v| block.call(hash, *v); hash}
end end
After which we can use to_h on Array and other enumarations :
a = [:count, nil].to_h do |hash, value| hash[value] = 1 if value end
=> {:count=>1}
P.S : I tired this by doing : rvm install 2.0.0-p0 && rvm use ruby-2.0.0-p0 rvm++ :)
Do feel free to share you liking towards any other new feature.
Update 0 thanks to Hanmac :
Some fun to ** and to_h.
Person = Struct.new(:name,:age) do alias to_hash to_h end
p [Person.new(“abc”,30)].map {|**p| p }
Would put : [{:name=>“abc”, :age=>30}]
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.