Reputation: 541
I have a file with space separated values:
Paul Smith 12345678
John Alex Doe 23456789
Lucy S Alena Blissett 34567890
And need to convert it to a hash like this:
{"Paul Smith"=>"12345678", "John Alex Doe"=>"23456789", "Lucy S Alena Blissett"=> "34567890"}
I can follow these tips for CSV but am a bit stumped by TSV and new line characters.
Thanks for any help!
Upvotes: 2
Views: 531
Reputation: 75488
Use String#scan and convert resulting array to hash:
File.read('file').scan(/^(.*)\s+([^\s]+)\r?$/).to_h
# => {"Paul Smith"=>"12345678", "John Alex Doe"=>"23456789", "Lucy S Alena Blissett"=>"34567890"}
Upvotes: 1
Reputation: 168101
Assuming that the format is not at all tab-separated value, but is separated by spaces:
s = <<_
Paul Smith 12345678
John Alex Doe 23456789
Lucy S Alena Blissett 34567890
_
s.scan(/(.+) (.+)/).to_h
result:
{
"Paul Smith" => "12345678",
"John Alex Doe" => "23456789",
"Lucy S Alena Blissett" => "34567890"
}
Upvotes: 7