Navaneeth Cp Navaneeth Cp - 5 months ago 6
Ruby Question

How to grep for a pattern in a file and store the content following it?

My file content is

blablabla

Name : 'XYZ'

Age : '30'

Place : 'ABCD'

blablabla

How can I grep for Name, Age, Place and store name XYZ, age 30 and place ABCD in a hash? What should be the '?' in below given code to get those details?

data = {}
name = /Name/
age = /Age/
place = /Place/
read_lines(file) { |l|
case l
when name
data[:name] = ?
when age
data[:age] = ?
when place
data[:place]= ?
end
}

Answer

You can use something like this.

data = {}
keys = {:name => "Name", :age => "Age", :place => "Place"}

File.open("test.txt", "r") do |f|
  f.each_line do |line|
    line.gsub!("\n", "")
    keys.each do |hash_key, string|
      if line[/#{string}/]
        data[hash_key] = line.strip.split(" : ")[-1].gsub("'", "")
      end
    end
  end
end

output

p data
# => {:name=>"XYZ", :age=>"30", :place=>"ABCD"}
Comments