0

The following code returns an error:

class ABC
  def self.method1()
    method2
  end

  def method2
  end
end

ABC.method1

NameError: undefined local variable or method `method2' for ABC:Class

However, the code below works fine:

class ABC
  def initialize
    method2
  end

  def method2
  end
end

ABC.new

Does initialize need to be used in order to properly define all methods within the class? What is wrong with the first code block?

3 Answers 3

3

You cannot call an instance method without having an object of that class.

method1 is a class method of class ABC, so you can call it on the class itself. But if you want to call your instance method method2, you need an object of class ABC rather than calling it on the class itself, ie.

o = ABC.new
o.method2

The other code works, because in initialize, you already have you instance of ABC, your method call can be understood as self.method2.

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

Comments

2

method1 is static, method2 not.

ABC.method2 is undefined, ABC.new.method2 is ok

class ABC

  def self.method1()
    method2    # ABC.method2
  end

  def initialize
    method2    # self.method2, self is instance of ABC
  end

  def method2
  end
end

1 Comment

Linguistic remark: 'Static' is a technical term, that it pays off to know, but is rarely used in Ruby itself. In Ruby, the most explicit way of calling such method is 'singleton method', or 'instance method of object's singleton class'. Singleton methods of classes (which are themselves objects like any others) are frequently nicknamed 'class methods', to distinguish them from instance methods of the class. For similar reasons, singleton methods of modules are nicknamed 'module methods'.
0

In first code block you try to call instance method in class method, it is like you call ABC.method2, but ABC does not have such method.

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.