Last Updated: February 25, 2016
·
544
· rmg

Ruby's conditional assignment masks private accessors!

This bit me the other day.. Using the conditional assignment operator (||=) creates a local variable.

class Foo
  def bar
    # creates local variable, shadowing private #priv()
    priv ||= 1
  end
  def baz
    # priv invokes private #priv()
    puts priv.inspect
  end
  private
  attr_accessor :priv
end

You have to use @priv ||= 1 or make the attr_accessor :priv protected instead of private and use self.priv ||= 1.