162 liens privés
DO :
1 == my_var
"my string" == my_string
DO NOT :
my_var == 1
my_string == 'my_string'
I guess you see where I'm going here : syntax error detected is much better than execution error. zero is great. What about the rest of integers ? What about strings ?
The = 0
instead of == 0
argument does not make much sense anymore, does it ?
My two cents.
I did not "invent" it, I was instructed to do it decades ago.
It took me some time to understand that sugar syntax.
First of : it's &
:to_s
obviously.
Operator is &
.
What does it do ?
it turns
mythings.map(& :upcase)
# is the same as
mythings.map(&:upcase)
into
mythings.map { |mything| mything.upcase }
Remark : sugar syntax can be a pain in the butt. I hope you do see it.
The map
method applies the "block" { |mything| mything.upcase }
on each and every elements of mythings
and returns an enumerable of class mythings.class
containing each result.
The operator is &
and the argument in my example is :upcase
. :upcase
is a Symbol
.
Symbols have a smart to_proc
method.
Another example :
require 'date'
[1,DateTime.now,3].map(&:to_s)
# => ["1", "2021-09-05T12:06:54+02:00", "3"]
So how does it work ?
-
&̀
when a parameter of a method is prepended with&
then ruby knows this parameter to be a Proc -
:upcase is a symbol.
So the &:myproc
is a smart shortcut implemented to turn the symbol :myproc
into a proc.
Let's try it :
def call_my_block ( my_parameter, &myblock)
myblock.call.myblock
end
The parameter &myblock
is known to be a block.
When I use method call_my_block
with the argument &:my_symbol
:
- The second parameter is known to be a block.
- The argument will be translated into
:my_symbol.to_proc
If the first argument is of classKlass
andKlass
actually has amy_symbol
method, then it will call it.
Example :
call_my_block DateTime.now , &:to_s
translates into :
:to_s.to_proc.call DateTime.now
note that :
a = :to_s.to_proc
#=> #<Proc:0x000055e77c191c98(&:to_s)>
a.call(13)
#=> "13"
a.class
#=> Proc
Hence :
call_my_block DateTime.now , &:to_s
# => "2021-09-05T12:06:00+02:00"
[1,DateTime.now,3].map { |val| call_my_block(val,&:to_s) }
#=> ["1", "2021-09-05T12:21:54+02:00", "3"]
[1,DateTime.now,3].map(&:to_s)
["1", "2021-09-05T12:23:22+02:00", "3"]
Note ::
- A function/methods has parameters.
- When called the function is given arguments
In other terms, an argument is the value of a parameter.