Main Content

Ruby - where one statement ends and the next begins

Archive - Originally posted on "The Horse's Mouth" - 2015-05-26 19:00:51 - Graham Ellis

In Ruby, you can end your statements with a ;, but it's more usual to simply let them end at the end of a line. Ruby can usually identify where a statement ends and if it clearly doesn't end on one line, it carries on to the next.

Just occasionally, this can be little bit of a trap. Look at this code with teo apparently identicsl statements giving different results. Why?

  a = 5
  b = a
    + 6
  puts b
  b = a +
    6
  puts b
  
  __END__
  
  trainee@kingston:~/lrp$ ruby ld
  5
  11
  trainee@kingston:~/lrp$


The answer is that Ruby has split the first "statement" into two - whereas the second example clearly continued from one line to the next and was treated as a single statement.

It's great to be teaching Ruby this week - see our Ruby Courses ... and I'll be going on to Cucumber and Gherkin over the next couple of days.