CS 3723
  Programming Languages  
  Ruby Lexical Level   

The programs below illustrate the way Ruby omits "needless" tokens at the end of lines, such at the semicolons and the do after the while and the then after the if. The third program below also leaves off parentheses, which can be omitted as long as the order is supposed to be left-to-right. Notice that I deliberately wrote the multiple assignement

    f0, f1, i, last = 0, 1, 0, 16
    

over two lines to show that Ruby handles a statement that cannot be syntatically finished at the end of a line. The tokens in the second program that are left off are shown in red. Ruby programmers almost always omit such tokens when they can.

Fibonacci number example
C Version Long Ruby Version Normal Ruby Version
#include <stdio.h>
int main() {
   int F0 = 0, F1 = 1, F2,
      i = 0, last = 30;
   while (i < last) {
      F2 = F0 + F1;
      printf("%i\t ", F0);
      F0 = F1; F1 = F2;
      i++;
      if (i%5 == 0)
         printf("\n");
   }
   
   printf("\n");
}

#!/usr/bin/ruby

f0 = 0; f1 = 1;
i = 0; last = 30;
while (i < last) do
  f2 = f0 + f1;
  printf("%i\t ", f0);
  f0 = f1; f1 = f2;
  i += 1;
  if (i%5 == 0) then
    printf("\n");
  end
end
printf("\n");
#!/usr/bin/ruby

f0, f1, i, last =
 0,  1, 0,  30
while i < last
  f2 = f0 + f1
  printf "%i\t ", f0
  f0, f1 = f1, f2
  i += 1
  if i%5 == 0
    printf "\n"
  end
end
printf "\n"
Common Output
0        1       1       2       3
5        8       13      21      34
55       89      144     233     377
610      987     1597    2584    4181
6765     10946   17711   28657   46368
75025    121393  196418  317811  514229


Revision date: 2013-03-11. (Please use ISO 8601, the International Standard Date and Time Notation.)