3

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?

0

2 Answers 2

9

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for help and showing me Struct and zip - I will read about these elements to fully understand them.
2

For simplicity, precision and clarity I'd do it like so:

"Mark Smith, 29" =~ /(\w+)\s+(\w+),\s+(\d+)/
  #=> 0 
{ :name=> $1, :surname=> $2, :age=> $3.to_i }
  #=> {:name=>"Mark", :surname=>"Smith", :age=>29} 

Unlike /\w+|\d+/, this regex requires "Mark" and "Smith" to be strings and "29" to be digits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.