Diane
Diane

Reputation: 21

Ruby Calling Class Method from Instance Method

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.

Upvotes: 2

Views: 2946

Answers (1)

tadman
tadman

Reputation: 211580

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

Upvotes: 5

Related Questions