Last active
August 29, 2015 14:13
-
-
Save joecorcoran/d9a0b38ec725fc9f12bf to your computer and use it in GitHub Desktop.
Working with yield in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Define a method named add_one that accepts | |
# a block and returns the return value of the | |
# block + 1, as follows. | |
# (Hint: yield gives you the return value of | |
# the block) | |
add_one do | |
2 | |
end | |
# => 3 | |
# Define a method named change_number that | |
# accepts an integer and a block, and returns | |
# an integer as follows. | |
# (Hint: yield can receive arguments) | |
n = 1 | |
change_number(n) do |x| | |
x + 10 | |
end | |
# => 11 | |
# Define a method named change_array that | |
# accepts an array and a block, and returns | |
# an array as follows. | |
# (Hint: you can call yield multiple times) | |
a = [1, 2, 3] | |
change_array(a) do |x| | |
x + 10 | |
end | |
# => [11, 12, 13] | |
# Further reading: Look at how map works: | |
# (http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-map) | |
# It's the same as our change_array method! | |
# Blocks are really useful for working with | |
# arrays and hashes. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment