Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the -> (dash greater than) operator in Ruby/Rails [duplicate]

I just ran across the following line of code in a Rails app:

scope :for_uid, ->(external_id) { where(external_id: external_id) }

What does the -> operator mean? It's kind of hard to Google.

like image 277
Javid Jamae Avatar asked Jul 15 '13 14:07

Javid Jamae


People also ask

What is the difference between || and or in Ruby?

|| has a higher precedence than or . So, in between the two you have other operators including ternary ( ? : ) and assignment ( = ) so which one you choose can affect the outcome of statements. Here's a ruby operator precedence table. See this question for another example using and / && .

What does double exclamation mark mean in Ruby?

Use the `!!` (Double-bang) Operator for Boolean Values In most programming languages, including Ruby, ! will return the opposite of the boolean value of the operand. So when you chain two exclamation marks together, it converts the value to a boolean.

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.


2 Answers

This is syntactic sugar.

->(external_id) { where(external_id: external_id) }

is equal to:

lambda { |external_id| where(external_id: external_id) }
like image 64
Marek Lipka Avatar answered Oct 14 '22 08:10

Marek Lipka


It's new lambda notation. This syntax was introduced in ruby 1.9, and is used to define unnamed functions.

In your example it is scope defined by unnamed function.

like image 33
samuil Avatar answered Oct 14 '22 08:10

samuil