dejay
dejay

Reputation: 768

How do I manipulate a variable that has been set to an object?

I have written a module similar to the following:

module One
  class Two
    def self.new(planet)
      @world = planet
    end
    def self.hello
      "Hello, #{@world}"
    end
  end
end

I was going to manipulate the module in the following way:

t = One::Two.new("World")
puts t.hello

Obviously, however, self.hello is not in t's scope. I realize that I could do the following:

t = One::Two
t.new("World")
puts t.hello

The previous method doesn't feel right, so I am looking for an alternative.

Upvotes: 0

Views: 92

Answers (2)

Ismael
Ismael

Reputation: 16730

You should create an initialize method and not a self.new to create objects of a class. SomeClass.new will call that initialize method.

If you want to access instance variables, you should do it using instance methods. So instead of def self.hello do def hello. If you want class methods you should also use class variables. To do so, instead of @some_var use @@some_var.

Upvotes: 1

Joshua Cheek
Joshua Cheek

Reputation: 31766

module One
  class Two
    # use initialize, not self.new
    # the new method is defined for you, it creates your object
    # then it calls initialize to set the initial state.
    # If you want some initial state set, you define initialize.
    # 
    # By overriding self.new, One::Two.new was returning the planet,
    # not an initialized instance of Two.
    def initialize(planet)
      @world = planet
    end

    # because One::Two.new now gives us back an instance,
    # we can invoke it
    def hello
      "Hello, #{@world}"
    end
  end
end

t = One::Two.new 'World'
t.hello # => "Hello, World"

Upvotes: 1

Related Questions