Skip to content

Instantly share code, notes, and snippets.

@russolsen
Created October 3, 2016 18:36
Show Gist options
  • Save russolsen/2ac25623ff1d0c7f6fcb946129bfc030 to your computer and use it in GitHub Desktop.
Save russolsen/2ac25623ff1d0c7f6fcb946129bfc030 to your computer and use it in GitHub Desktop.
Demo that in Ruby the for expression is just sugar around a call to the each method.
# Demo that for calls each
class ThreeOf
def initialize(value)
@value = value
end
def each(&block)
block.call(@value)
block.call(@value)
block.call(@value)
end
end
collection = ThreeOf.new(99)
for i in collection
puts i
end
puts "======="
collection.each {|i| puts i}
# And if that doesn't convince you...
class Array
alias_method :orig_each, :each
def each(*args, &block)
puts "Array Each called!"
orig_each(*args, &block)
end
end
puts "======="
puts "For loop with array"
for i in [1,2,3]
puts i
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment