Split into hash

L

Lee Jarvis

Ok guys, I have a file which looks something like this:

one=1
two=2
three=something
four=something else

I want to read each line into a hash, key=value..

I have tried something like

File.open('file').each do |line|
line.split(/=/){|a,b| #something}

but that's kind of how far i get.. The only way i know of is reading
them all into an array of arrays and turning that into a hash, Is there
a better idea?

Thanks in advance
 
L

Lee Jarvis

Ok now i have

a = Hash.new
File.open('file').each do |line|
b,c = line.split(/=/)
a = c
end


Which works, but im sure there are better ways out there?
 
S

Sebastian Hungerecker

Lee said:
Ok guys, I have a file which looks something like this:

one=1
two=2
three=something
four=something else

I want to read each line into a hash, key=value..

Hash[*File.read(filename).scan(/^.*=.*$/).flatten]


HTH,
Sebastian
 
R

Robert Klemme

Thanks very much everyone, That's a great help

Here's another one:

h = {}
File.foreach("file") do |line|
h[$1]=$2 if /^([^=]*)=([^=]*)$/ =~ line
end

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

File Contents into Hash Table? 6
String split into an array 2
Building a program that can enter data into a field 3
hash 6
Push regex search result into hash with multiple values 14
Split 10
Initialising a hash 46
hash 13

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top