尝试在Ruby中调用方法时出现异常

时间:2012-11-13 13:20:02

标签: ruby

我是Ruby新手。我的示例代码给了我这个例外:

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>'

使用退出代码1完成处理

我的代码是:

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

我使用的是RubyMine 4.5.4。

3 个答案:

答案 0 :(得分:3)

问题是你试图在类上调用first_method - 而first_method是一个实例方法。要调用实例方法,您需要使用该类的实例。要创建类的实例,可以使用SomeClass.new。因此,要使用您的方法,请尝试此代码(与@megas相同的代码):

class Hello
  def first_method
    puts "Hello World"
  end
end

Hello.new.first_method

答案 1 :(得分:3)

与其他答案(但要实现相同的输出)相比,如果您确实希望该方法调用在您的类中工作,您可以简单地将该方法定义为类方法:

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

#=> "Hello World"

我发现以下链接有助于更详细地解释两者之间的差异:http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

答案 2 :(得分:0)

试试这个:

class Hello
  def first_method
    puts "Hello World"
  end
end

Hello.new.first_method