`->` operator with scopes

96 Views Asked by At

What is the -> operator in the following?

scope :published, -> { where(published: true) }

scope is a method, :published is a symbol passed as an argument, which leads me to believe that -> { where(published: true) } makes up the next argument. -> is not a valid method name due to the presence of the > character.

1

There are 1 best solutions below

0
On BEST ANSWER

It is called lambda literal, and is just a short way of creating a lamda. Following are same:

double = -> (x) { 2 * x }
double.call(10) # => 20

is equivalent to:

double = lambda {|x| 2 * x }
double.call(10) # => 20

Incase you're not familiar with lambdas, then checkout ruby-doc for more details http://ruby-doc.org/core-2.0.0/Proc.html#method-i-lambda-3F

Also, checkout following StackOverflow thread What do you call the -> operator in Ruby?