Skip to content

Instantly share code, notes, and snippets.

@jccarbonfive
Created October 3, 2012 05:16
Show Gist options
  • Save jccarbonfive/3825156 to your computer and use it in GitHub Desktop.
Save jccarbonfive/3825156 to your computer and use it in GitHub Desktop.
enum = Enumerator.new do |yielder|
yielder << "a"
yielder << "b"
yielder << "c"
end
enum.next # "a"
enum.next # "b"
enum.next # "c"
enum.next # StopIteration: iteration reached an end
enum = Enumerator.new do |yielder|
yielder << 1
yielder << 2
end
loop do
puts enum.next
end
puts 'this will be printed out'
array = [1, 2, 3]
enum = array.to_enum
enum.each {|n| n * 2} # 2 4 6
array = [1, 2, 3]
enum = array.to_enum :map
enum.each {|n| n * 2} # [2, 4, 6]
enum.with_index {|n, index| [index, n ** 2]} # [[0, 1], [1, 4], [2, 9], [3, 16]]
array = [1, 2, 3, 4]
enum = array.select
enum.each {|n| n % 2 == 0} # [2, 4]
hash = { one: 1, two: 2 }
enum = hash.map
enum.each {|_, value| value * 10} # [10, 20]
range = 1..10
enum = range.drop_while
enum.each {|n| n < 7} # [7, 8, 9, 10]
file = File.new 'Rakefile'
enum = file.reject
enum.each {|line| line.length < 10} # ["#!/usr/bin/env rake\n",
"# Add your own tasks in files placed in lib/tasks ending in .rake,\n",
...]
Struct.new 'Foo', :name, :age
foo = Struct::Foo.new 'foo', 42
enum = foo.cycle
enum.take 5 # ["foo", 42, "foo", 42, "foo"]
enum = 5.times
enum.map { [] } # [[], [], [], [], []]
enum = 1.upto 10
enum.inject(:+) # 55
enum = 5.downto 0
enum.map {|n| n * 2} # [10, 8, 6, 4, 2, 0]
enum = "hello".each_char
enum.map &:upcase # ["H", "E", "L", "L", "O"]
enum = "abc".each_byte
enum.map {|n| n} # [97, 98, 99]
enum = "one\ntwo\nthree".each_line
enum.map {|line| line.chomp.reverse} # ["eno", "owt", "eerht"]
enum = 'a'.upto 'e'
enum.grep /[aeiou]/ # ["a", "e"]
enum = "one two three".gsub /\b\w+\b/
enum.next # "one"
enum.next # "two"
enum.next # "three"
enum = Enumerator.new do |yielder|
n = 0
loop do
yielder << n
n += 1
end
end
enum.first 10 # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
enum.select {|n| n % 20 == 0}.first 5 # never returns
class Enumerator
def lazy_select(&blk)
self.class.new do |yielder|
each do |n|
yielder << n if blk[n]
end
end
end
end
enum.lazy_select {|n| n % 20 == 0}.first 5 # [0, 20, 40, 60, 80]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment