![](/img/trans.png)
[英]How do I easily set devise in ruby on rails 3 to email forgotten password information?
[英]How do easily filter CSV data in Ruby
我正在處理一個 CSV 文件(大約 500 行)。 有沒有辦法使用過濾器從此文件中選擇數據。 我知道我可以通過解析 csv 並使用 select/find 方法在 ruby 中做到這一點,但我正在尋找一種更簡單的語法。 我不想編寫方法來處理以下每個查詢。 任何可以讓我做這些查詢的寶石? 我正在尋找一個非 Rails 解決方案,因為我正在編寫一個普通的 ruby 腳本。
例如
csv.find_rows(where: {'GENDER' => 'MALE'}.count
或者
csv.find_rows(where: {'GENDER' => 'MALE', 'SALARY' >= 10000 }
我認為你不需要寶石:
csv.select { |row| row['GENDER'] == 'MALE' }
csv.select { |row| row['GENDER'] == 'MALE' || row['SALARY'] >= 10000 }
如果你想要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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.