How to use an anonymous function in Ruby

2 Answers

0 votes
# Anonymous function = A function with no identifier.

# Anonymous function (lambda) that takes two numbers and returns their sum.
# ->(a, b) { a + b } is Ruby's concise lambda syntax.
add = ->(a, b) { a + b }

# Use the anonymous function
result = add.call(10, 20)

puts result


=begin
run:

30

=end

 



answered 1 day ago by avibootz
0 votes
# Anonymous function = A function with no identifier.

add = Proc.new { |a, b| a + b }

puts add.call(10, 20)


=begin
run:

30

=end

 



answered 1 day ago by avibootz
...