Exception when trying to call a method in Ruby

I am new to Ruby. My sample code gives me this exception:

C:/Users/abc/RubymineProjects/Sample/hello.rb:5:in `<class:Hello>': undefined method `first_method' for Hello:Class (NoMethodError) from C:/Users/abc/RubymineProjects/Sample/hello.rb:1:in `<top (required)>' from -e:1:in `load' from -e:1:in `<main>' 

Process terminated with exit code 1

My code is:

 class Hello def first_method puts "Hello World" end first_method() end 

I am using RubyMine 4.5.4.

+4
source share
3 answers

The problem is that you are trying to call first_method in the class - and first_method is the instance method. To call an instance method, you need to use an instance of the class. To create an instance of a class, you can use SomeClass.new . So, to use your method, try this code (same code as @megas):

 class Hello def first_method puts "Hello World" end end Hello.new.first_method 
+3
source

Unlike other answers (but to achieve the same output), if you want this method call to work in your class, you can simply define the method as a class method:

 class Hello def self.first_method puts "Hello World" end first_method() end #=> "Hello World" 

I found the following link useful to explain the difference between the two in more detail: http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

+3
source

Try the following:

 class Hello def first_method puts "Hello World" end end Hello.new.first_method 
0
source

Source: https://habr.com/ru/post/1445764/


All Articles