Created
October 24, 2012 16:08
-
-
Save mikesjewett/3947003 to your computer and use it in GitHub Desktop.
Each Method Explained
This file contains hidden or 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
# The each method is an iterator. It invokes a block of code a certain amount of times. The amount of times | |
# it will invoke the block of code depends on the size of the collection (array or hash) it is called on. | |
# for example, calling each on an array could be done like this: | |
[1,2,3].each do |num| | |
puts num | |
end | |
# this returns: | |
1 | |
2 | |
3 | |
=> [1,2,3] | |
# In the example above, the each method invoked a block of code that simply puts each element of the array. | |
# After the each method completed iterating, it returned the original array. | |
# The same example could be written more concisely as: | |
[1,2,3].each { |num| puts num } | |
# When it comes to code blocks: | |
# do == { | |
# end == } | |
# A common guideline for using {} vs do/end is if the block of code contains one line, use {}, otherwise, use do/end. | |
# Another important note from the example above is that 'num' is simply a variable that exists in the block of code. | |
# We could actually name it anything, but it's good practice to name it according to what it represents. | |
# In our case, num represents an element of the array [1,2,3]. So, with each iteration, it represents, 1, then 2, | |
# then 3. After the '3' iteration, there are no more elements to pass through the block of code, | |
# so the each method concludes, and returns the original array. |
This file contains hidden or 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
# Jaime's solution: | |
family=["mom", "dad", "Drew", "Alex", "June", "Leah", "Luca"] | |
message= "" | |
family.each do |name| | |
message=message + name + " I love you.\n" | |
end | |
puts message | |
# Alternative solution | |
# Regarding the '%w', I'm just showing you an alternative syntax for creating an array of strings. The curly brackets here are not used in the same manner as is blocks. %w{} creates an array just like [ ] does. | |
family = %w{ mom dad Drew Alex June Leah Luca } | |
message = "" | |
family.each { |name| message << "{name} I love you.\n" } # Since my block of code requires 1 line, I'm using {}. I also use the shovel (<<), which is nice way to build arrays and strings. | |
puts message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment