2

Is this the right way of calling an Instance method from a class method? Here the instance_var is passed with the Name object. I want to invoke func1 from the instance_var object passed to the class method.

I wrote this :

Class Name
    def initialize
        @name
    end
    def func1(value)
        puts value
    end
    def self.func2(instance_var,val)
        instance_var.func1(val)
    end
end
2
  • 1
    Why would you need this? But yeah, this would be the way to go, where instance_var is an instance of the Name class Commented Aug 3, 2012 at 10:38
  • I tried this, but value did not get printed. Commented Aug 3, 2012 at 10:48

1 Answer 1

3

How do you call func2?

Your code has a small error. You wrote Class instead class. With Class you get a syntax error.

This code works:

class Name
    def func1(value)
        puts value
    end
    def self.func2(instance_var,val)
        instance_var.func1(val)
    end
end

x = Name.new
Name.func2(x, 12)     #12

#or
Name.func2(Name.new, 12)  #12

Your

    def initialize
        @name
    end

will create an empty variable @name. It will never get a value. To assign a value you need:

class Name
    def initialize (var)
        @name = var
    end
end

x = Name.new(:x)
Sign up to request clarification or add additional context in comments.

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.