Ruby - CSV data finding


The find and find_all methods by the Enumerable module via Array can perform searches upon the data available in the array.

For example, you'd use this code to pick out the first person in the data called Java:


require 'csv'"test.txt", "w") do |f| 
  f.puts "Java,Manager,Logic,45\n" 
  f.puts "Json,Data,Female,23\n" 
  f.puts "Database,DBA,Female,38\n" 
end # from  w w w.  j av a  2s .c om

people ='text.txt') 
laura = people.find { |person| person[0] =~ /Java/ } 
puts laura.inspect


find method returns the first matching element of an array or hash.

find_all or select method returns all valid matches.

To find the people in your database whose ages are between 20 and 40:


require 'csv' 

people ='text.txt') 

young_people = people.find_all do |p|  #   w w  w .  ja  v a 2 s  .c om
  p[3].to_i.between?(20, 40) 
puts young_people.inspect


Related Topic