Hacker News new | ask | show | jobs
by matsadler 4433 days ago
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 = y
1 comments

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