J
Jeff Mitchell
def foo(*array)
array.each do |a|
# ...
end
end
Aha there's an asterisk so we know it's an array.
def foo2(&block)
@callback = block
# ..
end
Aha there's an ampersand so we know it's a block.
def foo3(what_is_this)
# ...
# (many lines of code)
# ...
what_is_this.each |key,value|
# ...
end
end
Hm what is what_is_this? <scroll scroll scroll> Aha I see it's the
ol' named-parameter thing.
But wait there's more! I can't do
foo4(some, variable, number, of, elements,
:then => some, :named => parameters)
because such a definition
foo4(*array, params)
# ...
end
would be illegal since params would be splatted into the array.
I propose:
def foo4(*array,%params,&block)
array.each do |a|
# ...
end
params.each do |key, value|
# ...
end
@callback = block
end
from above,
def foo3(%what_is_this)
# ...
end
Aha there's a percent sign so we know it's a hash.
It'll be backward compatible too. You'll just get the current
behavior when there's no percent sign. Also, the hash in
foo4( { :a => 4, :b => 5, :c => 6 } )
will be treated as a normal array argument.
To summerize, "%" gets us two things
(1) a nice signal to let everyone know a named parameter hash is
there
(2) the ability to mix variable-length arguments with named
parameters (in a nice way)
array.each do |a|
# ...
end
end
Aha there's an asterisk so we know it's an array.
def foo2(&block)
@callback = block
# ..
end
Aha there's an ampersand so we know it's a block.
def foo3(what_is_this)
# ...
# (many lines of code)
# ...
what_is_this.each |key,value|
# ...
end
end
Hm what is what_is_this? <scroll scroll scroll> Aha I see it's the
ol' named-parameter thing.
But wait there's more! I can't do
foo4(some, variable, number, of, elements,
:then => some, :named => parameters)
because such a definition
foo4(*array, params)
# ...
end
would be illegal since params would be splatted into the array.
I propose:
def foo4(*array,%params,&block)
array.each do |a|
# ...
end
params.each do |key, value|
# ...
end
@callback = block
end
from above,
def foo3(%what_is_this)
# ...
end
Aha there's a percent sign so we know it's a hash.
It'll be backward compatible too. You'll just get the current
behavior when there's no percent sign. Also, the hash in
foo4( { :a => 4, :b => 5, :c => 6 } )
will be treated as a normal array argument.
To summerize, "%" gets us two things
(1) a nice signal to let everyone know a named parameter hash is
there
(2) the ability to mix variable-length arguments with named
parameters (in a nice way)