Ruby Exercise 18 undefined method 虽然我定义了方法

标签 ruby learn-ruby-the-hard-way

你好,我在练习 18 中得到了错误“未定义的方法”,尽管我按照它写的那样做了。

class Exercise18_NamesVariablesCodeFunctions

# this one is like your scripts with ARGV
 def print_two(*args)
  arg1, arg2 = args
  puts "arg1: #{arg1}, arg2: #{arg2}"
 end

# ok, that *args is actually pointless, we can just do this
 def print_two_again(arg1, arg2)
  puts "arg1: #{arg1}, arg2: #{arg2}"
 end

# this just takes one argument
 def print_one(arg1)
  puts "arg1: #{arg1}"
 end

# this one takes no arguments
 def print_none()
  puts "I got nothin'."
 end


 print_two("Zed","Shaw")
 print_two_again("Zed","Shaw")
 print_one("First!")
 print_none()

end

这是我的错误:

exercise18_names_variables_code_functions.rb:25:in `<class:Exercise18_NamesVariablesCodeFunctions>': undefined method `print_two' for Exercise18_NamesVariablesCodeFunctions:Class (NoMethodError)
Did you mean?  print
    from exercise18_names_variables_code_functions.rb:1:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

我不明白这个错误。我定义了所有的方法。当我添加 self 。对它起作用的所有方法。

最佳答案

原因是来自类内部的任何方法调用都是调用类方法,而您定义的所有方法都是实例方法。

由于您当前编写的代码,您可以在定义类的实例后调用这些方法。

exercises = Exercise18_NamesVariablesCodeFunctions.new

exercises.print_two("Zed","Shaw") #=> "arg1: Zed, arg2: Shaw"

Exercises 是类本身的实例,因此可以访问该类的实例方法。

如果你想像现在一样调用这些方法,你需要将这些方法更改为类方法,但只需添加 self.在每个函数的名称之前

 def self.print_two(*args)
  arg1, arg2 = args
  puts "arg1: #{arg1}, arg2: #{arg2}"
 end

现在,您将能够从类内部调用该方法。

您还可以将所有类方法包装在一个容器中。

class Test
  class << self
    def first_method
    end

    def second_method
    end
  end
end

现在,class << self 中的任何方法是一个类方法。

关于Ruby Exercise 18 undefined method 虽然我定义了方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40060781/

相关文章:

ruby - 嵌套循环 : to be dynamic?

ruby - 要求命令在 Snow Leopard 上的 bash irb 中不起作用

ruby - 如何在 Ruby 中创建段落?

ruby-on-rails - 使用 Ruby on Rails 的单片和分布式系统

ruby - ruby 1.9.3 中是否存在与 prepend 方法等效的方法?

ruby - 我应该如何重新创建一个在 Fiddler in Ruby 中首次出现的 POST?

ruby - Rails3/ruby gem 中是否有将状态代码映射到消息的方法?

ruby-on-rails - 获取 Rails 中相关模型的列表