StandardNerd StandardNerd - 7 months ago 11
Ruby Question

ruby: how to initialize class method with parameters?

I'm struggling with a simple question how to instantiate a class with arguments.
For example i have a class with an initializer that takes two arguments and a class method:

class MyClass
attr_accessor :string_1, :string_2

def initialize(string_1, string_2)
@string_1 = string_1
@string_2 = string_2
end

def self.some_method
# do something
end

end


If some_method were an instance method i could instantiate a new object of MyClass and call the instance method like:

MyClass.new("foo", "bar").some_method


But how can i achieve that for the MyClass itself and the class method instead of an instance?

Something like MyClass.self("foo", "bar").some_method does not work.

Answer

You could do this.

class MyClass
  singleton_class.send(:attr_accessor, :string_3)
end

MyClass.string_3 = "It's a fine day."
MyClass.string_3 #=> "It's a fine day."

@string_3 is a class instance variable.