Skip to content

Instantly share code, notes, and snippets.

@cseder
Created April 19, 2017 18:53
Show Gist options
  • Select an option

  • Save cseder/1cdee876a40786e062fb30797631386c to your computer and use it in GitHub Desktop.

Select an option

Save cseder/1cdee876a40786e062fb30797631386c to your computer and use it in GitHub Desktop.
triangular_numbers = Enumerator.new do |yielder| number = 0
count = 1
loop do
number += count
count += 1
yielder.yield number
end
end
class Enumerator
def infinite_select(&block)
Enumerator.new do |yielder| self.each do |value|
yielder.yield(value) if block.call(value)
end
end
end
end
p triangular_numbers
.infinite_select {|val| val % 10 == 0}
.infinite_select {|val| val.to_s =~ /3/ }
.first(5)
@cseder
Copy link
Copy Markdown
Author

cseder commented Apr 19, 2017

Here’s an example that returns the first five triangular numbers that are multiples of 10 and that have the digit 3 in them.
Output:
[300, 630, 1830, 3160, 3240]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment