How to easily filter CSV data in Ruby

I am dealing with a CSV file (about 500 lines). Is there a way to select data from this filter file. I know that I can do this in ruby ​​by parsing csv and using select / find methods. But I'm looking for a simpler syntax. I do not want to write methods to handle each of the following requests. Any stone that would allow me to make these requests? I am looking for a solution without Rails as I am writing a simple ruby ​​script.

eg.

csv.find_rows(where: {'GENDER' => 'MALE'}.count

or

csv.find_rows(where: {'GENDER' => 'MALE', 'SALARY' >= 10000 }
+4
source share
2 answers

I don't think you need a gem here:

csv.select { |row| row['GENDER'] == 'MALE' }
csv.select { |row| row['GENDER'] == 'MALE' || row['SALARY'] >= 10000 }
+3
source

activerecord, activerecord ? CSV, , Sqlite, , , , .

require "csv"
require "sqlite3"
require "active_record"

# With activerecord
# Create our database table in to memory
ActiveRecord::Base.establish_connection(:adapter => "sqlite3",:database  => ":memory:")
unless ActiveRecord::Base.connection.table_exists?('searchengines')
  ActiveRecord::Schema.define do
    create_table :searchengines do |filename_table|
      filename_table.column :name, :string
      filename_table.column :url, :string
    end
  end
end

class Searchengine < ActiveRecord::Base
end

CSV.parse(DATA, headers: true) do |row|
  Searchengine.create({name: row[:name], url: row[:url]})
end

# or with plain sql

db = SQLite3::Database.new ":memory:"
rows = db.execute("create table searchengines (name varchar(30), url varchar(30))")

CSV.parse(DATA, headers: true) do |row|
  db.execute "insert into users values ( ?, ? )", row.fields
end

# then in activerecord

class Searchengine < ActiveRecord::Base
end

p Searchengine.where(name: "Google UK")

__END__
   Name, URL
Google UK, http://google.co.uk
Yahoo UK, http://yahoo.co.uk
-1

Source: https://habr.com/ru/post/1659713/


All Articles