[TOC]
Using block, proc, lambda or shorthand for devleoping easily. We don't need to code so many words and coding style is elegant.
We're often using the simplest way to code a map lambda method. A well-known example:
list = [2, 3, 4, 6, 1, 2, 3, 5]
list.map { |num| num + 3 }
# output >> [5, 6, 7, 9, 4, 5, 6, 8]If we're using the same block or lambda method. We're able to use kind of local variable
instead.
function = proc { |num| num + 3 }
list = [2, 3, 4, 6, 1, 2, 3, 5]
list.map(&function)
# output >> [5, 6, 7, 9, 4, 5, 6, 8]Sometimes you may call the method you made as like XXCLASS.xxmethod(xxVAR1, xxVAR2) or object
method. In this situation you could code as like below.
class Calculation
def self.add_five_times(num)
num * 5
end
end
list = [2, 3, 4, 6, 1, 2, 3, 5]
# Call a static method(Class Method).
list.map(&Calculation.method(:add_five_times))
# output >> [10, 15, 20, 30, 5, 10, 15, 25]Or a method in the same class you'd like to use in your map method.
def add_five_times(num)
num * 5
end
list = [2, 3, 4, 6, 1, 2, 3, 5]
# Call an object method or local method.
list.map(&method(:add_five_times))
# output >> [10, 15, 20, 30, 5, 10, 15, 25]list = [2, 3, 4, 6, 1, 2, 3, 5]
# Call an object method or local method.
list.map(&:to_s)
# output >> ["2", "3", "4", "6", "1", "2", "3", "5"]This is a big issue what I wanna know there is a good way for putting a element's method as parameter.
- Using
&method(:add_five_times)with the elements' method as parameters.