Skip to content

Instantly share code, notes, and snippets.

@rayning0
Last active October 28, 2021 22:29
Show Gist options
  • Save rayning0/6724800 to your computer and use it in GitHub Desktop.
Save rayning0/6724800 to your computer and use it in GitHub Desktop.
My_Each method, using Yield
# Read about the yield keyword and ruby blocks.
# http://allaboutruby.wordpress.com/2006/01/20/ruby-blocks-101/
# http://ruby.about.com/od/beginningruby/a/Block-Parameters-And-Yielding.htm
# http://blog.codahale.com/2005/11/24/a-ruby-howto-writing-a-method-that-uses-code-blocks/
# http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
# Now that you know how the yield method works, try to write your
# own version of the each method without using the each method
# provided by ruby. As in, try to build my_each using only the
# while keyword.
# Think about what's going on in each, if it's looping through
# the elements of an array and yielding you the individual
# element one at a time to your block. What has to happen
# to do this?
# Note: All ruby methods accept blocks by default.
# Creating my own "each" method, using "yield"
class Array
def my_each
if block_given?
i = 0
while i < self.size
yield(self[i])
i += 1
end
end
end
end
[2,10,12,15].my_each # no block
[2,10,12,15].my_each {puts 'Raymond'} # block and no parameter
[2,10,12,15].my_each {|e| puts e * e} # block and single parameter
# Output:
#Raymond
#Raymond
#Raymond
#Raymond
#4
#100
#144
#225
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment