Ruby - CSV data finding

Introduction

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:

Demo

require 'csv' 

File.open("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 = CSV.read('text.txt') 
laura = people.find { |person| person[0] =~ /Java/ } 
puts laura.inspect

Result

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:

Demo

require 'csv' 

people = CSV.read('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) 
end 
puts young_people.inspect

Result

Related Topic