Why do I need brackets in Ruby ... or Perl, Python, C or Java
Archive - Originally posted on "The Horse's Mouth" - 2010-09-29 08:30:25 - Graham Ellis
In many languages, you're required to put brackets around the boolean condition in your if and while statements, and around parameters you're passing to functions. And it becomes the natural way of coding for programmers in languages like Java, C and C++. But when you think about it, those brackets may be redundant syntax. What are brackets really used for?
Brackets are used to group things together. To say "do this first" if you want to override the BODMAS / BIDMAS precedence (Brackets, order/indeces, division, multiplication, addition, subtraction), and to evaluate all the parameters to a function before the function itself is called.
So --- if there is no ambiguity or precedence issue ---, it's logical that you can leave out the brackets. That's the case with Ruby ... and partially the case in Perl. Here's a Ruby example:
In the first line, there are brackets because there's a need to group the text strings with the appropriate puts, but in the other lines there isn't any precedence issue, and so the brackets have been dropped. See how it runs:
wizard:r11 graham$ ruby demo
a
b
nil
nil
-----------
c
d
wizard:r11 graham$
In some languages - such as Python - brackets after a function name have a somewhat different meaning - they actually instruct the language to run the code held in the variable rather than simply return a string about it:
def copyr():
print "This is mine"
return "empty bottle"
a = copyr
b = copyr()
print a,b
And that runs as follows:
wizard:r11 graham$ python pyrex
This is mine
<function copyr at 0x100475c08> empty bottle
wizard:r11 graham$