为什么我不能调用方法?

时间:2011-03-10 05:21:14

标签: ruby

所以我以为我会学习一些Ruby。我正在玩翻译,但我想制作更大的程序,所以我下载了Aptana,一个IDE。当我尝试运行此代码时:

class HelloWorld
    def h
        puts "hello World!"
    end
    h
end

它给出了一个错误,表示h是一个未定义的局部变量。当我将命令输入解释器(没有类的开始和结束)时,它会按照我想要的方式调用它。

我在这里不知所措。发生了什么事?

3 个答案:

答案 0 :(得分:3)

在定义类时,您定义的方法是instance方法。这意味着你会这样称呼它们:

class HelloWorld
  def h
    puts "hello world!"
  end
end

instance = HelloWorld.new
instance.h

Ruby抱怨你的方法不存在,因为在定义类体时,所做的任何函数调用都是class方法(或singleton方法)。

如果你真的想这样做,你会这样做:

class HelloWorld
  def self.h
    puts "hello World!"
  end
  h
end

答案 1 :(得分:0)

您的问题是,您在h范围内发送了class消息。 (我相信一些有更多Ruby经验的人会想要纠正我的措辞;而且,如果我完全错了,请接受我的道歉。)

您可以通过h上的其他实例方法发送HelloWorld

class HelloWorld
  def h; puts "hello world!"; end

  def g
    h
  end
end

HelloWorld.new.g
# => "hello world!"

答案 2 :(得分:0)

试试这个

class HelloWorld
  def self.h
    puts "hello World!"
  end
  h # you can only call h like this if it is defined as a class method above
end

HelloWorld.h # you can call the class method like this also

你需要将h定义为类方法来像这样调用它。或者,你可以这样做

class HelloWorld
  def h
    puts "hello World!"
  end
end

a = HelloWorld.new # instantiate a new instance of HelloWorld
a.h
祝你好运!

相关问题