Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between lambda and -> operator in Ruby

The following two scopes generate the same result, which syntax is preferable and is there any other difference?

scope :paid, lambda { |state| where(state: state) }

scope :paid, ->(state) { where(state: state) }
like image 752
Arif Avatar asked Jan 29 '15 12:01

Arif


People also ask

What does lambda do in Ruby?

You can run Ruby code in AWS Lambda. Lambda provides runtimes for Ruby that run your code to process events. Your code runs in an environment that includes the AWS SDK for Ruby, with credentials from an AWS Identity and Access Management (IAM) role that you manage.

What is difference between lambda and Proc in Ruby?

In Ruby, a lambda is an object similar to a proc. Unlike a proc, a lambda requires a specific number of arguments passed to it, and it return s to its calling method rather than returning immediately. proc_demo = Proc. new { return "Only I print!" }

What is the difference between procs and blocks?

When using parameters prefixed with ampersands, passing a block to a method results in a proc in the method's context. Procs behave like blocks, but they can be stored in a variable. Lambdas are procs that behave like methods, meaning they enforce arity and return as methods instead of in their parent scope.

How do you write lambda in Ruby?

Working with Lambdas in Ruby my_lambda_function = lambda { puts "Hello, Geeks !" } We have different ways to call this function. We can use my_lambda. call, my_lambda.


1 Answers

It's preferable, due to readibility reasons, to use new syntax -> (introduced in Ruby 1.9) for single-line blocks and lambda for multi-line blocks. Example:

# single-line
l = ->(a, b) { a + b }
l.call(1, 2)

# multi-line
l = lambda do |a, b|
  tmp = a * 3
  tmp * b / 2
end
l.call(1, 2)

It seems a community convention established in bbatsov/ruby-style-guide.

So, in your case, would be better:

scope :paid, ->(state) { where(state: state) }
like image 97
markets Avatar answered Oct 24 '22 10:10

markets