Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a class method within a class

Tags:

ruby

I realize this perhaps a naive question but still I cant figure out how to call one method from another in a Ruby class.

i.e. In Ruby is it possible to do the following:

class A
   def met1
   end
   def met2
      met1 #call to previously defined method1
   end
end

Thanks,

RM

like image 230
RomanM Avatar asked Dec 03 '08 01:12

RomanM


People also ask

How do you call a class method inside a class?

Example: public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called. Method2(); // Method being called. } // Method definition to call in another Method public static void Method1() { System.

Can we call method in class?

To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main. java).

How do you call a class method from another class method in Python?

Call method from another class in a different class in Python. we can call the method of another class by using their class name and function with dot operator. then we can call method_A from class B by following way: class A: method_A(self): {} class B: method_B(self): A.


1 Answers

Those aren't class methods, they are instance methods. You can call met1 from met2 in your example without a problem using an instance of the class:

class A
   def met1
     puts "In met1"
   end
   def met2
      met1
   end
end

var1 = A.new
var1.met2

Here is the equivalent using class methods which you create by prefixing the name of the method with its class name:

class A
   def A.met1
     puts "In met1"
   end
   def A.met2
      met1
   end
end

A.met2
like image 165
Robert Gamble Avatar answered Sep 27 '22 21:09

Robert Gamble