What Is "" in Ruby

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 is the difference between += and =+ in ruby?

There's no such token as =+; it's actually two tokens: assignment followed by the unary + operator; the latter is essentially a no-op, so @@num_things =+ 1 is equivalent to @@num_things = 1.

Since there is a += token, the language parser will parse it as a single token.

(In the early formulations of BCPL which was the precursor to C, the modern -= operator was written as =-.)

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 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.

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 @@variable mean in Ruby?

A variable prefixed with @ is an instance variable, while one prefixed with @@ is a class variable. Check out the following example; its output is in the comments at the end of the puts lines:

class Test
@@shared = 1

def value
@@shared
end

def value=(value)
@@shared = value
end
end

class AnotherTest < Test; end

t = Test.new
puts "t.value is #{t.value}" # 1
t.value = 2
puts "t.value is #{t.value}" # 2

x = Test.new
puts "x.value is #{x.value}" # 2

a = AnotherTest.new
puts "a.value is #{a.value}" # 2
a.value = 3
puts "a.value is #{a.value}" # 3
puts "t.value is #{t.value}" # 3
puts "x.value is #{x.value}" # 3

You can see that @@shared is shared between the classes; setting the value in an instance of one changes the value for all other instances of that class and even child classes, where a variable named @shared, with one @, would not be.

[Update]

As Phrogz mentions in the comments, it's a common idiom in Ruby to track class-level data with an instance variable on the class itself. This can be a tricky subject to wrap your mind around, and there is plenty of additional reading on the subject, but think about it as modifying the Class class, but only the instance of the Class class you're working with. An example:

class Polygon
class << self
attr_accessor :sides
end
end

class Triangle < Polygon
@sides = 3
end

class Rectangle < Polygon
@sides = 4
end

class Square < Rectangle
end

class Hexagon < Polygon
@sides = 6
end

puts "Triangle.sides: #{Triangle.sides.inspect}" # 3
puts "Rectangle.sides: #{Rectangle.sides.inspect}" # 4
puts "Square.sides: #{Square.sides.inspect}" # nil
puts "Hexagon.sides: #{Hexagon.sides.inspect}" # 6

I included the Square example (which outputs nil) to demonstrate that this may not behave 100% as you expect; the article I linked above has plenty of additional information on the subject.

Also keep in mind that, as with most data, you should be extremely careful with class variables in a multithreaded environment, as per dmarkow's comment.

what is [] operator in Ruby

It depends if you're talking about array literals or those brackets used for getting or assigning values from/to arrays or hashes.

As a literal, [] is just an array literal, shorthand for writing Array.new. You also asked about {}, which is a hash literal, i.e. shorthand for writing Hash.new. Parentheses are not literals (or 'operators' for that matter) – they're used to group things.

As an 'operator' for getting or assigning values, as others have pointed out in the comments, [] isn't special or conceptually different from other 'operators'.

In the same way 2 + 3 is sugar for writing 2.+(3), writing array[0] is sugar for writing array.[](0).

The reason this works is that arrays have a method that's literally called []. You can find it by getting all the methods on an array:

[].methods
# => long array including :[] (and also :[]=, by the way, for assignments)

Note that the brackets in [].methods are an array literal, not an 'operator'.

I haven't looked at the implementation of any Ruby interpreters, but my guess is they see something like array[0] and convert it to array.[](0) (or at least they treat it as such). That's why this kind of sugar syntax works and looks like 'operators' even though it's all methods under the hood.

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 to my_object. Any
object can be a receiver but depending on the method's visibility
sending a message may raise a NoMethodError.

You may use &. to designate a receiver, then my_method is not invoked
and the result is nil when the receiver is nil. In that case, the
arguments of my_method are not evaluated.



Related Topics



Leave a reply



Submit