What does ||= (or-equals) mean in Ruby?

2018-12-31 03:04发布

What does the following code mean in Ruby?

||=

Does it have any meaning or reason for the syntax?

20条回答
泛滥B
2楼-- · 2018-12-31 03:12

This is the default assignment notation

for example: x ||= 1
this will check to see if x is nil or not. If x is indeed nil it will then assign it that new value (1 in our example)

more explicit:
if x == nil
x = 1
end

查看更多
何处买醉
3楼-- · 2018-12-31 03:13

||= is called a conditional assignment operator.

It basically works as = but with the exception that if a variable has already been assigned it will do nothing.

First example:

x ||= 10

Second example:

x = 20
x ||= 10

In the first example x is now equal to 10. However, in the second example x is already defined as 20. So the conditional operator has no effect. x is still 20 after running x ||= 10.

查看更多
人气声优
4楼-- · 2018-12-31 03:14

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.

查看更多
像晚风撩人
5楼-- · 2018-12-31 03:19
a ||= b

is equivalent to

a || a = b

and not

a = a || b

because of the situation where you define a hash with a default (the hash will return the default for any undefined keys)

a = Hash.new(true) #Which is: {}

if you use:

a[10] ||= 10 #same as a[10] || a[10] = 10

a is still:

{}

but when you write it like so:

a[10] = a[10] || 10

a becomes:

{10 => true}

because you've assigned the value of itself at key 10, which defaults to true, so now the hash is defined for the key 10, rather than never performing the assignment in the first place.

查看更多
怪性笑人.
6楼-- · 2018-12-31 03:20

Concise and complete answer

a ||= b

evaluates the same way as each of the following lines

a || a = b
a ? a : a = b
if a then a else a = b end

-

On the other hand,

a = a || b

evaluates the same way as each of the following lines

a = a ? a : b
if a then a = a else a = b end

-

Edit: As AJedi32 pointed out in the comments, this only holds true if: 1. a is a defined variable. 2. Evaluating a one time and two times does not result in a difference in program or system state.

查看更多
大哥的爱人
7楼-- · 2018-12-31 03:22

In short, a||=b means: If a is undefined, nil or false, assign b to a. Otherwise, keep a intact.

查看更多
登录 后发表回答