Reputation: 41
I am new to Ruby. My sample code is giving 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 finished 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.
Upvotes: 4
Views: 70
Reputation: 684
In contrast to the other answers (but to achieve the same output), if you did want that method call to work within your class you could 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 to be helpful in explaining the difference between the two in a little more detail: http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/
Upvotes: 3
Reputation: 35783
The problem is that you are trying to call first_method
on the class -- and first_method
is an instance method. To call an instance method, you need to use an instance of the class. To make an instance of the 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
Upvotes: 3
Reputation: 21791
Try this:
class Hello
def first_method
puts "Hello World"
end
end
Hello.new.first_method
Upvotes: 0