How to grep for a digit after a word and a space in a file and process it in ruby -


for example, file file.txt containts

total 60
maths 20
physics 15
chemistry 25
bla bla 10
bla bla bla 15

now need grep total,maths,physics,chemistry values , check whether total=maths+physics+chemistry or not.
how can in ruby?

here 1 way:

data = {} file.open("/path/to/data_file", "r") |f|     f.each_line |l|         # split line around non-white space chars         # last element in split result marks, rest parts of subject         *v1, v2 = l.chomp.split(/\w+/)          # use subject name key , marks value          data[v1.join(' ')] = v2.to_i     end end  p data #=> {"total"=>60, "maths"=>20, "physics"=>15, "chemistry"=>25,  #    "bla bla"=>10, "bla bla bla"=>15}  # let's remove :total hash, left  # individual subject's marks total_marks = data.delete("total")  # add total of specific subjects added_total = data.values_at("maths", "physics", "chemistry").reduce(:+)  # if sum of subjects needed, un-comment below line # added_total_all = data.values.reduce(:+)  puts "total: #{total_marks}, sum of marks: #{added_total}" #=> total: 60, sum of marks: 60 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -