While having a chat with Keith about the meaning of the term 'syntactic sugar', he pointed out that my examples weren't strictly that. The methods times and each for numbers and arrays aren't technically syntax of Ruby, just things you can do with Ruby.
A more accurate example of 'syntactic sugar' would be something like this:
# this:
blah = Blah.new({:arg1 => 'something', :p => 'something else'})
# could be written like this:
blah = Blah.new :arg1 => 'something', :p => 'something else'
Braces and parenthesis are generally optional for method arguments and are normally only used to resolve which argument belongs to which method when passing methods as arguments to other methods. The syntax is so much cleaner when not having to include operators where their use is unnecessary.
Recently I started learning Ruby and I have to say: I can easily see it becoming my favourite language
. Firstly, I would like to thank Keith Rowell for getting me to give Ruby a go and for helping me unlearn some tendencies learnt from other languages (ocassionally referred to as PHPisms and Pythonisms
).
Ruby is full of what many describe as 'syntactic sugar' and makes writing in the language a dream. For example, every number is an object and has methods:
# Will print out the word "hello" five times
5.times { puts "hello" }
Arrays (as with pretty much everything in Ruby) are also objects and have their own methods:
# Will print out the numbers one to five
[1,2,3,4,5].each { |n| puts n }
Ruby also comes with an interactive Ruby shell that you can test things out in. Just open a command prompt and enter 'irb'. You can then try out the two examples above and see what they do for yourself.
To learn more about Ruby stay tuned because I have a feeling that you will be hearing (or reading as the case clearly is) a lot more about Ruby from me. Until next time, you can read up on Ruby at ruby-lang.org and ruby-doc.org.