How to Pass an Argument With Ruby Lambda Literal Syntax (->)?

In a Ruby lambda literal syntax (->), you can accept an argument in the following way:

# Ruby 1.9+
my_lambda = ->(name) { puts "Hello, #{name}!" }

Prior to Ruby version 2.x, there should not be any space between the arrow (->) and the argument in the lambda literal syntax. If a space is present, it will result in a syntax error. However, in Ruby version 2.x and later, a space between the arrow and the argument is allowed but not required.

In the code above, the lambda is defined with a single argument called "name". You can use this "name" variable within the lambda's body to perform any desired operations.

To invoke the lambda and pass an argument, you can use the Proc#call method, for example, like so:

my_lambda = ->(name) { puts "Hello, #{name}!" }

my_lambda.call("John") #=> "Hello, John"

Alternatively, you can invoke the lambda and pass an argument to it using the "[]" shorthand syntax, for example, like so:

my_lambda = ->(name) { puts "Hello, #{name}!" }

my_lambda["John"] #=> "Hello, John"

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.