I just started to learn Ruby!
I have the following string:
"Mark Smith, 29"
and I want to convert it to hash, so it looks like this:
{:name=>"Mark", :surname=>"Smith", :age=>29}
I've written the following code, to cut the input:
a1 = string.scan(/\w+|\d+/)
Now I have an array of strings. Is there an elegant way to convert this to hash? I know I can make three iterations like this:
pers = Hash.new
pers[:name] = a1[0]
pers[:surname] = a1[1]
pers[:age] = a1[2]
But maybe there is a way to do it using .each method or something like this? Or maybe it is possible to define a class Person, with predefined keys (:name, :surname, :age), and then just "throw" my string to an instance of this class?
Yes, you can do like,
%i(name surname age)
.zip(string.scan(/\w+|\d+/))
.to_h
# => {:name=>"Mark", :surname=>"Smith", :age=>"29"}
Or, you can take the benefit of Struct, like:
Person = Struct.new(:name, :surname, :age )
person = Person.new( *string.scan(/\w+|\d+/) )
person.age # => "29"
person.name # => "Mark"
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