Skip to content

Commit

Permalink
Added support to sort tabular data.
Browse files Browse the repository at this point in the history
  • Loading branch information
hopsoft committed May 28, 2015
1 parent 98c08e3 commit a9effa3
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 4 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,12 @@ mined.to_a
The first entry is the header row.
Subsequent entries are data rows.
The last value in each data row indicates the number of matches.

Need to sort the rows? Just pass a `sort_by` block.

```ruby
# sort on "total" i.e. 3rd value in the row
mined.to_a do |row|
row[2]
end
```
4 changes: 3 additions & 1 deletion lib/goldmine/hash_miner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,15 @@ def pivoted_keys

# Returns pivoted data as a tabular Array that can be used to build CSVs or user interfaces.
# @return [Array] Tabular pivot data
def to_a
# @yield [Array] sort_by block for sorting the Array
def to_a(&block)
rows = map do |pair|
[].tap do |row|
row.concat pair.first.values
row << pair.last.size
end
end
rows = rows.sort_by(&block) if block_given?
header = pivoted_keys.map(&:to_s) << "total"
rows.insert 0, header
rows
Expand Down
2 changes: 1 addition & 1 deletion lib/goldmine/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Goldmine
VERSION = "1.1.1"
VERSION = "1.1.2"
end
10 changes: 8 additions & 2 deletions test/test_goldmine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,14 @@ class TestGoldmine < PryTest::Test
record[:age] >= 21
end

expected = [["Name has an 'e'", ">= 21 years old", "total"], [false, true, 2], [true, true, 2], [true, false, 1]]
assert mined.to_a == expected
expected = [["Name has an 'e'", ">= 21 years old", "total"], [true, false, 1], [false, true, 2], [true, true, 2]]

# block is sort_by
tabular_data = mined.to_a do |row|
[row[2], row[0] ? 1 : 0, row[1] ? 1 : 0]
end

assert tabular_data == expected
end

test "source_data" do
Expand Down

0 comments on commit a9effa3

Please sign in to comment.