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.
|| 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 / && .
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.
=~ 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.
This is syntactic sugar.
->(external_id) { where(external_id: external_id) }
is equal to:
lambda { |external_id| where(external_id: external_id) }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With