Created
May 18, 2010 15:03
-
-
Save suzukimilanpaak/405097 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 | 鈴木 達矢 | 19800324 | 1 | |
---|---|---|---|---|
3 | Matthew Day | 19850324 | 0 | |
5 | 人見 裕 | 19811103 | 3 | |
2 | Jerome Kumori | 19880505 | 1 | |
4 | Agata Znamienkiewicz | 19821213 | 0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a code snippet to analyse CSV file. This program has got functions to sort, filter by value of each column and availability of a row. | |
# To run this program copy payroll.rb and payroll.csv to somewhere same place in your disc and just run it by ruby command. | |
# $ ruby payroll.rb | |
require 'csv' | |
class Payroll | |
# Indexes for columns | |
COLUMN_NUM = 0 | |
COLUMN_NAME = 1 | |
COLUMN_BDAY = 2 | |
COLUMN_AVAILABLE = 3 | |
# Order of sort | |
ASC = 0 | |
DESC = 1 | |
def initialize(filepath) | |
@rows = [] | |
CSV.open(filepath, 'r', ',') { |row| @rows << row} | |
end | |
# show contents of a CSV file | |
def show(only_available = false) | |
puts '-------------------------------' | |
@rows.each do |row| | |
if only_available | |
puts row.join('| ') if row[COLUMN_AVAILABLE] == "1" | |
else | |
puts row.join('| ') | |
end | |
end | |
puts '-------------------------------' | |
end | |
def sort!(column = COLUMN_NUM, order = ASC) | |
if order == ASC | |
@rows.sort!{|a, b| a[column].to_i <=> b[column].to_i} | |
else | |
@rows.sort!{|a, b| b[column].to_i <=> a[column].to_i} | |
end | |
self | |
end | |
def filter!(keyword, column = COLUMN_NAME) | |
if column == COLUMN_NAME | |
@rows = @rows.select{|row| row[column] =~ /#{keyword}/ } | |
else | |
@rows = @rows.select{|row| row[column] == keyword } | |
end | |
self | |
end | |
end | |
# a)Sort rows by specified column in Asc/Desc | |
Payroll.new("payroll.csv").sort!(Payroll::COLUMN_NUM, Payroll::ASC).show | |
Payroll.new("payroll.csv").sort!(Payroll::COLUMN_BDAY, Payroll::DESC).show(true) | |
# b)Search row by specified column matching fully | |
Payroll.new("payroll.csv").filter!("19821213", Payroll::COLUMN_BDAY).show | |
Payroll.new("payroll.csv").filter!("鈴木 達矢", Payroll::COLUMN_NAME).show | |
# c)Search row like a specified keyword | |
# Search row(s) whose name column contains "e" and "i" | |
Payroll.new("payroll.csv").filter!("e", Payroll::COLUMN_NAME).filter!("i", Payroll::COLUMN_NAME).show(true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment