Introducing the syntax of Ruby

I’m five chapters and three sections into Eloquent Ruby and the Code Academy. As I’m ok at Java and Actionscript, a fair amount of the learning process so far is just noting the syntactical differences. For example, no need for semi-colons, ‘else if’ becomes ‘elsif‘, snake_case for everything except classes (UPPER_SNAKE_CASE for constants), methods are declared with def method_name, et cetera.

One difference that I’ve decided I really like, is the usage of ‘unless’ in place of ‘if not’ and ‘until’ in place of ‘while not’. When written well, Ruby is often written as speech thanks to seemingly minor additions such as this.

Take for example this snippet to print odd numbers between 10 and 0:

1
2
3
4
5
n = 10
while n != 0 do
  puts n if n % 2 != 0
  n -= 1
end

Written a different way…

1
2
3
4
5
n = 10
until n == 0 do
  puts n unless n % 2 == 0
  n -= 1
end

Maybe it’s just personal tastes, but I much prefer the look of the latter.

Leave a Reply

Your email address will not be published. Required fields are marked *

*