【问题标题】:Ruby Exercise 18 undefined method although i defined the methodsRuby 练习 18 未定义的方法虽然我定义了方法
【发布时间】:2016-10-15 15:18:26
【问题描述】:

您好,我在练习 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>'

我不明白这个错误。我定义了所有的方法。当我添加自我。它适用于所有方法。

【问题讨论】:

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


    【解决方案1】:

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

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

    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 &lt;&lt; self 中的任何方法都是类方法。

    【讨论】:

      【解决方案2】:

      尝试关注。

      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
      
      a = Exercise18_NamesVariablesCodeFunctions.new
      
       a.print_two("Zed","Shaw")
       a.print_two_again("Zed","Shaw")
       a.print_one("First!")
       a.print_none()
      
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-25
        • 2010-10-15
        • 1970-01-01
        • 1970-01-01
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多