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 ||= (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 is -() { } in Ruby?
It is a lambda literal. Put the block variables inside ()
and the body inside {}
.
->(x, y){x + y}
In the example, ->(v){v}
takes a single argument v
and returns it, in other words, it is an identity function. If a block is passed to method
, then that is assigned to c
. If not, the identity function is assigned to c
as default.
Can someone please explain what (:+) is in Ruby?
A colon :
before a sequence of characters* is a Symbol
literal. This applies to :+
, which is a Symbol
with content "+".
A symbol can be used to reference a method with the same name in some contexts, and in a couple of places your example :+
can be a reference to the +
operator, which is really just a method with the same name. Ruby supports syntax to call it when it sees a plain +
in an expression, or in some core methods it will convert :+
As an example you can use :+
as shorthand to create a sum of an Array
of integers:
[1,2,3,4].inject( :+ )
=> 10
This works because Ruby has special-cased that specific use of operators in Array#inject
(actually defined in Enumberable#inject
, and Array
gets it from that module).
A more general use-case for a symbol like this is the send
method:
2.send( :+, 2 )
=> 4
Although 2.send( "+", 2 )
works just fine too. It might seem odd when used like this instead of just 2 + 2
, but it can be handy if you want to make a more dynamic choice of operator.
*
The rules for the syntax allowed or not allowed in a Symbol
literal are a little arcane. They enable you to write shorter literals where possible, but Ruby has to avoid some ambiguous syntax such as a Symbol
with a .
or whitespace in the middle. This is allowed, just you have to add quotes if you generate such a Symbol
e.g. :"this.that"
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
In Ruby what does = mean and how does it work?
=>
separates the keys from the values in a hashmap literal. It is not overloadable and not specifically connected to symbols.
A hashmap literal has the form {key1 => value1, key2 => value2, ...}
, but when used as the last parameter of a function, you can leave off the curly braces. So when you see a function call like f(:a => 1, :b => 2)
, f
is called with one argument, which is a hashmap that has the keys :a
and :b
and the values 1
and 2
.
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.
@ variables in Ruby on Rails
title
is a local variable. They only exists within its scope (current block)
@title
is an instance variable - and is available to all methods within the class.
You can read more here:
http://strugglingwithruby.blogspot.dk/2010/03/variables.html
In Ruby on Rails - declaring your variables in your controller as instance variables (@title
) makes them available to your view.
What does mean in Ruby?
It can have 3 distinct meanings:
'<<' as an ordinary method
In most cases '<<' is a method defined like the rest of them, in your case it means "add to the end of this array" (see also here).
That's in your particular case, but there are also a lot of other occasions where you'll encounter the "<<" method. I won't call it 'operator' since it's really a method that is defined on some object that can be overridden by you or implemented for your own objects. Other cases of '<<'
- String concatenation: "a" << "b"
- Writing output to an IO: io << "A line of text\n"
- Writing data to a message digest, HMAC or cipher: sha << "Text to be hashed"
- left-shifting of an OpenSSL::BN: bn << 2
- ...
Singleton class definition
Then there is the mysterious shift of the current scope (=change of self) within the program flow:
class A
class << self
puts self # self is the singleton class of A
end
end
a = A.new
class << a
puts self # now it's the singleton class of object a
end
The mystery class << self
made me wonder and investigate about the internals there. Whereas in all the examples I mentioned <<
is really a method defined in a class, i.e.
obj << stuff
is equivalent to
obj.<<(stuff)
the class << self
(or any object in place of self) construct is truly different. It is really a builtin feature of the language itself, in CRuby it's defined in parse.y as
k_class tLSHFT expr
k_class
is the 'class' keyword, where tLSHFT
is a '<<' token and expr
is an arbitrary expression. That is, you can actually write
class << <any expression>
and will get shifted into the singleton class of the result of the expression. The tLSHFT
sequence will be parsed as a 'NODE_SCLASS' expression, which is called a Singleton Class definition (cf. node.c)
case NODE_SCLASS:
ANN("singleton class definition");
ANN("format: class << [nd_recv]; [nd_body]; end");
ANN("example: class << obj; ..; end");
F_NODE(nd_recv, "receiver");
LAST_NODE;
F_NODE(nd_body, "singleton class definition");
break;
Here Documents
Here Documents use '<<' in a way that is again totally different. You can define a string that spans over multiple lines conveniently by declaring
here_doc = <<_EOS_
The quick brown fox jumps over the lazy dog.
...
_EOS_
To distinguish the 'here doc operator' an arbitrary String delimiter has to immediately follow the '<<'. Everything inbetween that initial delimiter and the second occurrence of that same delimiter will be part of the final string. It is also possible to use '<<-', the difference is that using the latter will ignore any leading or trailing whitespace.
Related Topics
Safe Navigation Equivalent to Rails Try for Hashes
How to Use the Ruby "Self" Keyword
How to Test If All Items in an Array Are Identical
How to Allow Binary File Download Using Grape API
Read Contents of a Local File into a Variable in Rails
How to Run a Simple File on Heroku
Rspec: How to Write a Test That Expects Certain Output But Doesn't Care About the Method
What Is the Point of Object#Presence in Rails
Conditional Haml - If Else Nesting
Run a Cli Thor App Without Arguments or Task Name
How to Remove All Elements That Satisfy a Condition in Array in Ruby
Ruby Gem Listed, But Won't Load (Gem in User Dir, Not Ruby Dir)