||=' Operator in Ruby

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

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's the difference between or and | in ruby?

The | operator is a binary mathematical operator, that is it does a binary OR and works on a numerical level:

1 | 2
# => 3
4 | 3
# => 7
1 | 2 | 3
# => 3

This is because it's manipulating individual values as if they were binary:

0b01 | 0b10
# => 3 (0b11)

The || operator is a logical one, that is it returns the first value that's logically true. In Ruby only literal nil and false values evaluates as logically false, everything else, including 0, empty strings and arrays, is true.

So:

1 || 2
# => 1
0 || 1
# => 0

The or operator works almost exactly the same as || except it's at a much lower precedence. That means other operators are evaluated first which can lead to some problems if you're not anticipating this:

a = false || true
# => true
a
# => true

a = false or true
# => true
a
# => false

This is because it's actually interpreted as:

(a = false) or true

This is because = has a higher precedence when being evaluated.

Clarification on the Ruby Operator

Ruby is an object-oriented language. The fundamental principle of object orientation is that objects send messages to other objects, and the receiver of the message can respond to the message in whatever way it sees fit. So,

a << b

means whatever a decides it should mean. It's impossible to say what << means without knowing what a is.

As a general convention, << in Ruby means "append", i.e. it appends its argument to its receiver and then returns the receiver. So, for Array it appends the argument to the array, for String it performs string concatenation, for Set it adds the argument to the set, for IO it writes to the file descriptor, and so on.

As a special case, for Fixnum and Bignum, it performs a bitwise left-shift of the twos-complement representation of the Integer. This is mainly because that's what it does in C, and Ruby is influenced by C.

Ruby ** double star operator

** is Exponent Operator- It performs exponential (power) calculation. Let me explain by this simple example

2 ** 2 => 2 * 2 => 4

2 ** 3 => 2 * 2 * 2 => 8

2 ** 4 => 2 * 2 * 2 * 2 => 16

2 ** 5 => 2 * 2 * 2 * 2 * 2 => 32

so 43 ** 67 => 43 * 43 * 43 * 43 ...............................................................

so it results in such a big number.

To get more details on operatorts http://www.tutorialspoint.com/ruby/ruby_operators.htm

Ruby ternary operator (or) or operator

The difference here is that, for example, [].present? or ''.present? both return false. So:

question = ''
@question = question.present? ? question : Question.new
# => result of Question.new
@question = question || Question.new
# => ''

But it shouldn't mean anything in your case if question can only hold nil or Question instance (which is always present, assuming it's a regular ActiveRecord model). So it's more a matter of personal taste.

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.

||=' operator in Ruby

It's an assignment operator for 'Conditional Assignment'

See here -> http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators

Conditional assignment:

 x = find_something() #=>nil
x ||= "default" #=>"default" : value of x will be replaced with "default", but only if x is nil or false
x ||= "other" #=>"default" : value of x is not replaced if it already is other than nil or false

Operator ||= is a shorthand form of the expression:

x = x || "default" 

EDIT:

After seeing OP's edit, the example is just an extension of this, meaning:

car = method_1 || method_2 || method_3 || method_4

Will assign the first non-nil or non-false return value of method_1, method_2, method_3, method_4 (in that order) to car or it'll retain its old value.

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



Related Topics



Leave a reply



Submit