StandardNerd StandardNerd - 5 months ago 9x
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

def self.some_method
# do something


If some_method were an instance method i could instantiate a new object of MyClass and call the instance method like:"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.


You could do this.

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

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

@string_3 is a class instance variable.