James Gray
8/30/2006 5:07:00 PM
On Aug 30, 2006, at 11:01 AM, Drew Olson wrote:
> Let me be more specific: essentially I want to find the groups of rows
> that share an element. Let's say each row in my CVS doc has 3
> elements.
> I want to iterate across every group of rows that share the same value
> for the first element. Hope this makes sense.
I'm assuming you meant CSV (not CVS). ;)
See if this gets you going:
Firefly:~/Desktop$ cat data.csv
one,1,A
one,2,B
one,3,C
two,1,A
two,2,B
three,1,A
Firefly:~/Desktop$ irb -r csv
>> rows = CSV.read("data.csv")
=> [["one", "1", "A"], ["one", "2", "B"], ["one", "3", "C"], ["two",
"1", "A"], ["two", "2", "B"], ["three", "1", "A"]]
>> groups = rows.map { |row| row.first }.uniq
=> ["one", "two", "three"]
>> groups.each do |group|
?> puts group
>> rows.select { |row| row.first == group }.each { |row| puts " #
{row.inspect}" }
>> end
one
["one", "1", "A"]
["one", "2", "B"]
["one", "3", "C"]
two
["two", "1", "A"]
["two", "2", "B"]
three
["three", "1", "A"]
=> ["one", "two", "three"]
James Edward Gray II