user1820873
user1820873

Reputation: 41

Exception while trying to call a method in Ruby

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

Answers (3)

donovan.lampa
donovan.lampa

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

Linuxios
Linuxios

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

megas
megas

Reputation: 21791

Try this:

class Hello
  def first_method
    puts "Hello World"
  end
end

Hello.new.first_method

Upvotes: 0

Related Questions