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

Question!

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 this code to get those?

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
}


Answers
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.chomp!
    keys.each do |hash_key, string|
      if line[/#{string}/]
        data[hash_key] = line.strip.split(" : ")[-1].gsub("'", "")
        break
      end
    end
  end
end

output

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


Strange code, but in this case:

  data[:name] = l.split(':')[1] if l.match(name)
when age
  data[:age] = l.split(':')[1] if l.match(age)
when place
  data[:place]= l.split(':')[1] if l.match(place)

Are you interested in refactoring?

One option is to:

mapping =
    [
        { name: :name, pattern: /Name/ },
        { name: :age, pattern: /Age/ },
        { name: :place, pattern: /Place/ }
    ]
data = str.split(/\r?\n|\r/).map do |line|
  mapping.map{|pair|
    { pair[:name] => line.split(' : ')[1].gsub("'", "") } if line.match(pair[:pattern])
  }.compact.reduce({}, :merge)
end.reduce({}, :merge)


Suppose we first read the file into a string:

str = File.read('fname')

which is:

str =<<_
blablabla
Name : 'XYZ'
Age : '30'
Place : 'ABCD'
blablabla
_
  #=> "blablabla\nName : 'XYZ'\nAge : '30'\nPlace : 'ABCD'\nblablabla\n"

Then use the regex

r = /
    ^                    # match beginning of line 
    Name\s*:\s*'(.*)'\n  # match 'Name`, ':' possibly surrounded by spaces, any number
                         # of any character in capture group 1, end of line
    Age\s*:\s*'(.*)'\n   # match 'Age`, ':' possibly surrounded by spaces, any number
                         # of any character in capture group 2, end of line
    Place\s*:\s*'(.*)'\n # match 'Place`, ':' possibly surrounded by spaces, any number
                         # of any character in capture group 3, end of line
    /x                   # free-spacing regex definition mode

with String#scan to form the hash:

[:name, :age, :place].zip(str.scan(r).first).to_h
  #=> {:name=>"XYZ", :age=>"30", :place=>"ABCD"} 


This video can help you solving your question :)
By: admin