Ruby trap

Content:

Another little weirdness that I saw on LinkedIn. I am not linking because I prefer a different example to illustrate.

class X
    def v
        @v
    end
    def initialize(v)
        @v = v
    end
    def dump
        print "v = #{v} (#{v!=nil})"
    end
end

o = X.new(123)
o.dump()

Output:

v = 123 (true)
class X
    def v
        @v
    end
    def initialize(v)
        @v = v
    end
    def dump
        if false
            v = 456
        end
        print "v = #{v} (#{v!=nil})"
    end
end

o = X.new(123)
o.dump()

Output:

v =  (false)

So what is going on here? Well - the Ruby language has some rules that cause this.

        if false
            v = 456
        end

This creates a method local variable v no matter the flow. If the block had been executed then the value would have been 456, but now when the block is not executed then the value is nil.

        print "v = #{v} (#{v!=nil})"

This use the method local variable v instead of the instance property v.

Ouch!!

Comments: