Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string to hash values

Tags:

ruby

hash

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?

like image 886
Maciek Avatar asked Jul 16 '26 03:07

Maciek


1 Answers

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"
like image 137
Arup Rakshit Avatar answered Jul 17 '26 19:07

Arup Rakshit