There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
Agree with a comment or answer? Like () to up-vote the contribution!
I am not sure if this will work for posting a question but here we go.
With this iterator layout or format:
odds = [1,3,5,7,9]
odds.each {|x| print x * 2}
How do I make sure a comma is added after each result?
Thank you.
Note the effect that end braces have: They denote the boundaries of a code block. There is no do or end in that syntax.
odds.each { |x| print x }
Since x is a block parameter it is not the same as the x you have on line 5, which is undefined at that point and should rightly raise an exception (throw a fatal error).
Note that print does not move the draw pencil so each value is on the same line. To print on separate lines use, puts which includes a newline afterward (meaning the pencil is shifted to the beginning of the next line).
odds.each do |x|
print x * 2
end
Note there are no end braces. do implies the start of a block, and end represents the end of the block. The block scope is the same as that of the curly brace block. Witness that both forms have the parameter variable inside the block.
One would be best to practice using both, even when only one form is expected. Complete a lesson, get the check marks, but don’t leave the page. Go back over your code and write it in the other form (without removing the other code) and run it. The result on the screen should be the same. Let yourself get used to recognizing both forms.
When it comes to the unit on Blocks, Procs and Lambdas you will be glad to have this in your toolkit. The block syntax ({}) is very much in use with those objects.