StandardNerd
StandardNerd

Reputation: 4183

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.

Upvotes: 1

Views: 6086

Answers (2)

Jared
Jared

Reputation: 661

I believe the conventional way to initiate a class and then run a method on those values would be like:

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

  def some_method
    "#{@string_1} #{@string_2}"
  end
end

a = MyClass.new("foo", "bar")
puts a.some_method #=> "foo bar"

If you want to use attr_accessor then you can bypass the some_method to return those values:

class MyClass 
  attr_accessor :string_1, :string_2
  def initialize(string_1, string_2)
    @string_1 = string_1
    @string_2 = string_2
  end
end

a = MyClass.new("foo", "bar")
puts a.string_1 + a.string_2 #=> "foobar"

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110755

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.

Upvotes: 2

Related Questions