EngineerWho EngineerWho - 27 days ago 6
Ruby Question

Calling a singleton method within the singleton class in Ruby?

Consider the following Ruby code:

module MyModule
class << self

def process_item(item)
item.capitalize
end

def foo=(item)
@foo_ref=process_item(item)
end

def foo
@foo_ref
end

self.foo = "initial foo"
end
end


I want to set a default
foo_ref
variable inside the singleton class definition. However, the Ruby interpreter raises the following error:


singleton class': undefined method `foo=' for #(NoMethodError)


If I change
self.foo = "Initial foo"
to
foo = "Initial foo"
then I am creating a local variable within the singleton class, instead of calling the setter method.

Also, I do realize that I may have to put the
process_item
method in the module definition, outside the singleton class definition, so that it does not become a singleton method, but rather a helper method.

What would be the proper approach to this code (being able to call a singleton method within the singleton class definition, and having helper methods available within the singleton class definition)?

Answer

You can define the default value as:

module MyModule
  class << self

    def process_item(item)
      item.capitalize
    end

    def foo=(item)
      @foo_ref=process_item(item)
    end

    def foo
      @foo_ref ||= "initial foo"
    end
  end
end

What you were trying to do was to set foo to the singleton class, instead of setting foo to the class.

Comments