Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ruby, Reading a file, containing name/value pairs into a hash

Tags:

ruby

I have a file that has a name/value pair on each line, I want to open the file, read each line and initialize a hash.

file:

john, 234
joe, 2222

And load a hash so I can loop through the key value pairs.

like image 993
Blankman Avatar asked Nov 07 '10 21:11

Blankman


People also ask

How do I get the Hash value in Ruby?

Convert the key from a string to a symbol, and do a lookup in the hash. Rails uses this class called HashWithIndifferentAccess that proves to be very useful in such cases.

How do you make Hash Hash in Ruby?

Ruby hash creation. A hash can be created in two basic ways: with the new keyword or with the hash literal. The first script creates a hash and adds two key-value pairs into the hash object. A hash object is created.

What can be a Hash key in Ruby?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.


2 Answers

Hash[*File.read('f.txt').split(/[, \n]+/)]
like image 76
DigitalRoss Avatar answered Oct 19 '22 17:10

DigitalRoss


f = <<EOF
john, 234
joe, 2222
EOF

p Hash[*f.split(/, |\n/)]

The method #split gives an array looking like ["john,", "234", "joe,", "2222"]. The * (AKA splat) operator converts this array to a bunch of arguments. Hash#[] takes this bunch of arguments (when there are an even number of arguments) and delivers a hash.

like image 27
steenslag Avatar answered Oct 19 '22 18:10

steenslag