Skip to content

Commit

Permalink
adds Enumerable#mapping alias for #collecting
Browse files Browse the repository at this point in the history
  • Loading branch information
bmabey committed Aug 25, 2011
1 parent c85d6ac commit 3b1dcc8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
4 changes: 2 additions & 2 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Enumerating extends Enumerable with "lazy" versions of various common operations

* `#selecting` selects elements that pass a test block (like `Enumerable#select`)
* `#rejecting` selects elements that fail a test block (like `Enumerable#reject`)
* `#collecting` applies a transforming block to each element (like `Enumerable#collect`)
* `#collecting`/`#mapping` applies a transforming block to each element (like `Enumerable#collect` and `#map`)
* `#uniqing` discards duplicates (like `Enumerable#uniq`)
* `#taking`, `#taking_while`, `#dropping` and `#dropping_while` also do what you expect

Expand All @@ -28,7 +28,7 @@ Perhaps an example would help. Consider the following snippet:
9^2 = 81
10^2 = 100
=> [1, 4, 9, 16]

Here we use plain old `#collect` to square a bunch of numbers, and then grab the ones less than 20. We can do the same thing using `#collecting`, rather than `#collect`:

>> (1..10).collecting { |x| puts "#{x}^2 = #{x*x}"; x*x }.take_while { |x| x < 20 }
Expand Down
22 changes: 12 additions & 10 deletions lib/enumerating/filtering.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,33 @@ def each
end

module Enumerable

def collecting
Enumerating::Filter.new do |output|
each do |element|
output.call yield(element)
end
end
end


alias mapping collecting

def selecting
Enumerating::Filter.new do |output|
each do |element|
output.call(element) if yield(element)
end
end
end

def rejecting
Enumerating::Filter.new do |output|
each do |element|
output.call(element) unless yield(element)
end
end
end

def uniqing
Enumerating::Filter.new do |output|
seen = Set.new
Expand All @@ -63,18 +65,18 @@ def uniqing_by
end
end
end

def taking(n)
Enumerating::Filter.new do |output|
if n > 0
each_with_index do |element, index|
output.call(element)
output.call(element)
break if index + 1 == n
end
end
end
end

def taking_while
Enumerating::Filter.new do |output|
each do |element|
Expand All @@ -83,7 +85,7 @@ def taking_while
end
end
end

def dropping(n)
Enumerating::Filter.new do |output|
each_with_index do |element, index|
Expand All @@ -92,7 +94,7 @@ def dropping(n)
end
end
end

def dropping_while
Enumerating::Filter.new do |output|
taking = false
Expand All @@ -102,6 +104,6 @@ def dropping_while
end
end
end

end

0 comments on commit 3b1dcc8

Please sign in to comment.