【问题标题】:Ruby method visibility: undefined method? [closed]Ruby 方法可见性:未定义的方法? [关闭]
【发布时间】:2012-09-07 12:23:26
【问题描述】:

我还是 ruby​​ 的新手。我不明白方法的可见性。文档说,默认情况下所有方法都是公共的(除非另有定义)。所以这应该有效(但它没有,MWE):

modules/example.rb:

class Example

  def do_stuff
    puts 'hello world'
  end

end

testing.rb:

load 'modules/example.rb'

Example.new
Example.do_stuff

致电$ ruby testing.rb 结果

testing.rb:9:in `<main>': undefined method `do_stuff' for Example:Class (NoMethodError)

有人能解释为什么吗?以及如何解决我可以直接调用do_stuff

【问题讨论】:

  • 不知道为什么这被否决了?投票赞成

标签: ruby methods visibility nomethoderror


【解决方案1】:

您正在定义一个实例方法,并且需要在 Example 类的实例上调用它:

ex_instance = Example.new
ex_instance.do_stuff

如果要直接调用,需要将其定义为类方法:

class Example

  def self.do_stuff
    puts 'hello world'
  end

end

那么你可以这样调用它而不需要调用Example.new

Example.do_stuff

【讨论】:

  • 谢谢。我瞎了——那真是太愚蠢了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 1970-01-01
  • 2019-07-25
  • 2019-12-25
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多