1

I can get a method that sets an instance variable in a singleton class to work if it does not end with =:

class Aaa
  class << self
    def config(&block)
      instance_eval(&block)
    end

    def set_blah(blah)
      @blah = blah
    end

    def blah
      @blah
    end
  end
end

Aaa.config {set_blah("something")}
Aaa.blah # => "something" as expected

When the method that sets the instance variable ends with a =, it doesn't work anymore:

class Bbb
  class << self
    def config(&block)
      instance_eval(&block)
    end

    def blah=(blah)
      @blah = blah
    end

    def blah
      @blah
    end
  end
end

Bbb.config {blah=("something")}
Bbb.blah # => nil, not sure why

# This works
Bbb.blah=("hi")
Bbb.blah # => "hi"

Why are the set_blah and blah= methods working differently?

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Powers
  • 18,150
  • 10
  • 103
  • 108

1 Answers1

3

Just calling blah= will create a local variable named blah and assign it the value of ("something"), which is "something". You have to add explicit receiver e.g.:

self.blah=("something")
ndnenkov
  • 35,425
  • 9
  • 72
  • 104