What does ||= (or-equals) mean in Ruby?
This question has been discussed so often on the Ruby mailing-lists and Ruby blogs that there are now even threads on the Ruby mailing-list whose only purpose is to collect links to all the other threads on the Ruby mailing-list that discuss this issue.
Here's one: The definitive list of ||= (OR Equal) threads and pages
If you really want to know what is going on, take a look at Section 11.4.2.3 "Abbreviated assignments" of the Ruby Language Draft Specification.
As a first approximation,
a ||= b
is equivalent to
a || a = b
and not equivalent to
a = a || b
However, that is only a first approximation, especially if a
is undefined. The semantics also differ depending on whether it is a simple variable assignment, a method assignment or an indexing assignment:
a ||= b
a.c ||= b
a[c] ||= b
are all treated differently.
What does the (unary) * operator do in this Ruby code?
The *
is the splat operator.
It expands an Array
into a list of arguments, in this case a list of arguments to the Hash.[]
method. (To be more precise, it expands any object that responds to to_ary
/to_a
, or to_a
in Ruby 1.9.)
To illustrate, the following two statements are equal:
method arg1, arg2, arg3
method *[arg1, arg2, arg3]
It can also be used in a different context, to catch all remaining method arguments in a method definition. In that case, it does not expand, but combine:
def method2(*args) # args will hold Array of all arguments
end
Some more detailed information here.
what does this syntax mean in Ruby? .. tasks.all?(&:complete?)
&
is for passing block to method as a block (also used the other way in parameter list to make implicit block a parameter), it implicitly calls to_proc
on passed object.
Symbol#to_proc
for :symbol
makes a proc{|param| param.symbol }
So your code is equvalent to tasks.all?{|task| task.complete? }
what does ? ? mean in ruby
Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false.
When you write a function that can only return true or false, you should end the function name with a question mark.
The example you gave shows a ternary statement, which is a one-line if-statement. .nil?
is a boolean function that returns true if the value is nil and false if it is not. It first checks if the function is true, or false. Then performs an if/else to assign the value (if the .nil?
function returns true, it gets nil as value, else it gets the File.join(root_dir, '/')
as value.
It can be rewritten like so:
if root_dir.nil?
prefix = nil
else
prefix = File.join(root_dir, '/')
end
What does ||= mean?
Basically, a ||= b
means assign b to a if a is null or undefined or false (i.e. false-ish value in ruby)
, it is similar to a = b unless a
, except it will always evaluate to the final value of a
(whereas a = b unless a
would result in nil
if a
was true-ish).
What does this mean in Ruby language?
head, *tail = a
means to assign the first element of the array a
to head
, and assign the rest of the elements to tail
.
*
, sometimes called the "splat operator," does a number of things with arrays. When it's on the left side of an assignment operator (=
), as in your example, it just means "take everything left over."
If you omitted the splat in that code, it would do this instead:
head, tail = [1, 2, 3, 4, 5]
p head # => 1
p tail # => 2
But when you add the splat to tail
it means "Everything that didn't get assigned to the previous variables (head
), assign to tail
."
What does &. (ampersand dot) mean in Ruby?
It is called the Safe Navigation Operator. Introduced in Ruby 2.3.0, it lets you call methods on objects without worrying that the object may be nil
(Avoiding an undefined method for nil:NilClass
error), similar to the try
method in Rails.
So you can write
@person&.spouse&.name
instead of
@person.spouse.name if @person && @person.spouse
From the Docs:
my_object.my_method
This sends the
my_method
message tomy_object
. Any
object can be a receiver but depending on the method's visibility
sending a message may raise aNoMethodError
.You may use
&.
to designate a receiver, thenmy_method
is not invoked
and the result isnil
when the receiver isnil
. In that case, the
arguments ofmy_method
are not evaluated.
What do you call the - operator in Ruby?
In Ruby Programming Language ("Methods, Procs, Lambdas, and Closures"), a lambda defined using ->
is called lambda literal.
succ = ->(x){ x+1 }
succ.call(2)
The code is equivalent to the following one.
succ = lambda { |x| x + 1 }
succ.call(2)
Informally, I have heard it being called stabby lambda or stabby literal.
What is Ruby's double-colon `::`?
::
is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup:
module SomeModule
module InnerModule
class MyClass
CONSTANT = 4
end
end
end
You could access CONSTANT
from outside the module as SomeModule::InnerModule::MyClass::CONSTANT
.
It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot .
).
Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes
Related Topics
State MAChine, Model Validations and Rspec
Rails Error Message Displays Key and I Only Want Value
Nokogiri Issues with Ruby on Rails
Compass Error for Command 'Grunt Server'
Require Ruby File Without .Rb Extension
How to Render a Layout Directly from Routes.Rb, Without a Controller
How to Install Rmagick Gem on Windows
Problem Installing Ruby 1.9.2 on MAC Os Lion
Dynamically Create a Class Inherited from Activerecord
Rails Reload Dynamic Routes on Multiple Instances/Servers
How Are Respond_To and Respond_To_Missing Different
How to Capture a Part of a Screen Using Ruby on Windows
Requiring a Ruby Gem in Ruby Script Breaks Cron Job Execution
Why Is 032 Different Than 32 in Ruby
Why Does 'Puts(Nil or 4)' Fail in Ruby
Ruby Convert Single Quotes to Double Quotes in Xml
What Could Be Causing This Rails Ioerror Closed Stream
If 'Self' Is Always the Implied Receiver in Ruby, Why Doesn't 'Self.Puts' Work