Misunderstanding between {} and do/end


#1

Hello,

From what I understand from the lesson, it seems that putting the iterator between {} was the same than starting it with ´do´and ending it with ´end´.

  • Excercise 12. Try it out

However, when using the brackets solution, I get an error message (see below) that I don’t get when using the do/end method.

Can someone explain where am I mistaken ? Thanks !

  • Error message + code with the brackets :

(ruby):2: syntax error, unexpected tIDENTIFIER, expecting '}'
odds.each {|item|item*=2 print"#{item}"}


odds = [1,3,5,7,9]

odds.each {|item|item*=2 print"#{item}"}


  • Code with do/end, result appears correctly in the prompt window:
odds = [1,3,5,7,9]

odds.each do|item|
  item*=2 
  print"#{item}"
end


#2

That is two statements inside the block so needs a separator, ;. However, you are also mutating the block variable, which does not make logical sense.

odds.each { |item| print "#{item * 2}" }

Same thing with do block:

odds.each do |item|
    print "#{item * 2}"
end

#3

Great thank you mtf ! I tried both methods and it worked. I’ll rememeber the separator ´;´ for next time.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.