I am kinda new to Ruby and still trying to understand some of the language design principles. IF I've got it right, the lambda expression call in Ruby must be with square braces, while the "regular" function call is with "regular"/round braces.
Is there a special reason that the syntax is different? Or, in other words, (why) should the caller be aware whether they call a function or apply a lambda expression?
Regular Ruby method calls use
()
not curly braces which are for blocks. If you don't like[]
for calling a lambda, you can always use thecall
method.Example:
Edit
In newer version of Ruby also:
As to why you can't just do
by_two(5)
, when Ruby sees a bareword it first tries to resolve it as a local variable and if that fails as a method.Because in Ruby, methods are not lambdas (like, for example, in JavaScript).
Methods always belong to objects, can be inherited (by sub-classing or mixins), can be overwritten in an object's eigenclass and can be given a block (which is a lambda). They have their own scope for variables. Example method definition:
However lambdas/procs are plain closures, maybe stored in a variable - nothing else:
Ruby combines both approaches with a powerful syntax, for example, passing blocks:
If you want brackets, you can do
Note the
.
betweenby_two
and(5)
.