I would like to know the meaning of this piece of code for find one possible bug:
-> a, b, c, d, e, f, g, h, i, j {
l = -> s, t = c {
Math.log(s, t)
}
}
Thank you
I would like to know the meaning of this piece of code for find one possible bug:
-> a, b, c, d, e, f, g, h, i, j {
l = -> s, t = c {
Math.log(s, t)
}
}
Thank you
The first part: -> a, b, c, d, e, f, g, h, i, j { ... }
is declaration of a lambda, or anonymous function.
where a,b,c... and so on are arguments to be passed as variables inside the block {..}
This is the same as: lambda { |a,b,c,...j| ... }
You can see a similar example here:
ex1 = -> a,b,c,d {
puts a;
puts b;
puts c;
}
ex1.call('1', '2', '3', '4');
Then it returns another lambda inside of it:
l = ->
s, t = c {Math.log(s, t)
as denoted by the ->
symbol, and defaults t
argument to previously supplied c
arg in the outer lambda.
Finally it call Math.log on s and t arguments from the inner lambda.
Here's a simplified version:
ex2 = -> a,b { c = -> d, e = b { puts d; puts e } }
ex2.call(1,2).call(3) # e is optional since it's defaulted to b
# => 3,2
Note: Your code is missing some }
.
To be honest, this code is absolutely horrible. I'd be surprised to learn that there's only one bug.
Here's a rewrite:
weird_log = lambda do |_, _, default_base, _, _, _, _, _, _, _|
lambda do |x, base=default_base|
Math.log(x, base)
end
end
It's a bit more readable and it makes it clear that the method signature is useless. In the original code, only c
is used from the 10 original arguments.
a, b, d, e, f, g, h, i, j
aren't used so they can be renamed to _
. They need to be specified, though, even if they aren't used:
weird_log.call(nil, nil, 10)
#=> ArgumentError: wrong number of arguments (given 3, expected 10)
weird_log.call(nil, nil, 10, nil, nil, nil, nil, nil, nil, nil)
#=> #<Proc:0x00000000031e57c8@(pry):9 (lambda)>
weird_log.call(nil, nil, 10, nil, nil, nil, nil, nil, nil, nil).call(100)
#=> 2.0
weird_log.call(nil, nil, 10, nil, nil, nil, nil, nil, nil, nil).call(100, Math::E)
# => 4.605170185988092
A less cryptic way would be to write:
def my_log(base = Math::E)
->(x) { Math.log(x, base) }
end
It can be used this way:
log10 = my_log(10)
# => #<Proc:0x000000000222d2b8@(irb):2 (lambda)>
log10.call(100)
# => 2.0
natural_log = my_log
#=> #<Proc:0x0000000002243540@(irb):2 (lambda)>
natural_log.call(10)
#=> 2.302585092994046
But then, you might as well use Math.log
directly:
Math.log(100, 10)
# => 2.0
Math.log(10)
# => 2.302585092994046