2

What is the syntax for calling a class method from an instance method? Suppose I have the following

class Class1
    def initialize
       #instance method
       self.class.edit
       puts "hello"
    end

    def self.edit
       #class method
       "ha"
    end
end

c= Class1

When I run this code, I get no outputs.

1
  • Try Class1.new. initialize is an instance method, so it must be invoked on an instance of Class1. Class1.new creates the instance, invokes initialize on it and then returns the instance. Commented Oct 23, 2016 at 2:48

1 Answer 1

5

You don't get any output because you don't do anything with the result of that call, plus you don't actually create an instance with new, you just make c an alias for that class. If you change it a bit you get this:

class Class1
    def initialize
       #instance method
       puts self.class.edit
    end

    def self.edit
       #class method
       "ha"
    end
end

c= Class1.new
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.