The difference between a = a || b and a || = b

I read Ruby Programming, The Pick Ax Book, and the author claims that there is a difference between:

var = var || "Default Value"

and

var || = "Default Value"

I do not understand this, because there is no difference with what I see. Can anyone help me with this?

+4
source share
2 answers

Resource citation here :

In a = a || b, a is set by something according to the instructions on each run, whereas with || a = b, a is set only when a is logically false (i.e., if it is zero or false), because || "short circuit". That is, if the left side || the comparison is correct, there is no need to check the right side.

, , dev, , .

EDIT: , a || a = b a ||= b. :

a , || a = 42 Error, || || 42 42. , .

, , , Ruby , ( a ||= 42).

, , :)

Ruby , || a = 42, , .

+3

, getter setter:

class Foo
  def var
    puts 'Foo#var called'
    @var
  end
  def var=(value)
    puts 'Foo#var= called'
    @var = value
  end
end

, Foo#var= :

f = Foo.new
f.var = f.var || "Default Value"
# Foo#var called
# Foo#var= called
f.var = f.var || "Default Value"
# Foo#var called
# Foo#var= called

Foo#var= :

f = Foo.new
f.var ||= "Default Value"
# Foo#var called
# Foo#var= called
f.var ||= "Default Value"
# Foo#var called
+3

Source: https://habr.com/ru/post/1623864/


All Articles