Re:Ruby Tips, Part 5
by riffraff on Tuesday April 22, 2014 @03:47PM
(#7629949)
notice that this is wrong
it's actually something slightly different (or at least it was some years ago).
[ Parent
| on HN ]
Here's an example that shows x ||= y behaves like x || x = y, rather than x = x || y
class Foo
def foo=(object)
puts "foo= called with #{object.inspect}"
@foo = object
end
def foo
puts "foo called"
@foo
end
end
puts "x || x = y"
a = Foo.new
a.foo || a.foo = 1
a.foo || a.foo = 2
puts "\nx = x || y"
b = Foo.new
b.foo = b.foo || 1
b.foo = b.foo || 2
puts "\nx ||= y"
c = Foo.new
c.foo ||= 1
c.foo ||= 2
This outputs: x || x = y
foo called
foo= called with 1
foo called
x = x || y
foo called
foo= called with 1
foo called
foo= called with 1
x ||= y
foo called
foo= called with 1
foo called
and you can see that the output for ||= matches the output for x || x = yI didn't mean that it is "x = x || y", I meant "it's completely ad hoc".
For example, if you try "x || x = y" you will get an exception if x is not defined, but "x ||= y" will work fine. The same is true of constants "X || X = 1" will explode while "X ||= 1" will work fine.