1

How can a class method (inside a module) update an instance variable? Consider the code bellow:

module Test

  def self.included(klass)
    klass.extend ClassMethods
  end

  module ClassMethods

    def update_instance_variable
     @temp = "It won't work, bc we are calling this on the class, not on the instance."
     puts "How can I update the instance variable from here??"
    end

  end

end


class MyClass
  include Test
  attr_accessor :temp
  update_instance_variable

end

m = MyClass.new # => How can I update the instance variable from here??
puts m.temp     # => nil
3
  • 2
    Why do you want to do this? By definition instance variables only make sense when you have an instance of the class. At present your update_instance_variable call will only execute once when the class is defined. Are you trying to arrange for some instance variables to have default values? Commented Aug 3, 2010 at 19:12
  • mikej is right, what you're doing is wrong-headed. Commented Aug 4, 2010 at 0:18
  • I know, when the code update_instance_variable is executed, there is not instance to be updated (only instances of class class). Ok. But must be a way to set default values for the class dynamically. I could use define_method to define initialize, and inside define the default values of the instance variable, but I just want to know if there is a different way of doing... Commented Aug 4, 2010 at 4:10

2 Answers 2

2

You'd have to pass your object instance to the class method as a parameter, and then return the updated object from the method.

Sign up to request clarification or add additional context in comments.

Comments

0

That does nto quite make sense. You use the initialize method to set default values.

class MyClass
  attr_accessor :temp

  def initialize
    @temp = "initial value"
  end

end

The initialize method is automatically run for you when you create a new object. When your class declaration is run, there are no, and cannot be any, instances of the class yet.

If you want to be able to change the default values later you can do something like this:

class MyClass
  attr_accessor :temp

  @@default_temp = "initial value"

  def initialize
    @temp = @@default_temp 
  end

  def self.update_temp_default value
    @@default_temp = value
  end

end

a = MyClass.new
puts a.temp
MyClass.update_temp_default "hej"
b = MyClass.new
puts b.temp

prints

initial value
hej

If you also want that to change already created instances' variables you need additional magic. Please explain exactly what you wish to accomplish. You are probably doing it wrong :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.