【问题标题】:Argument Error : Wrong number of arguments参数错误:参数数量错误
【发布时间】:2016-01-18 12:06:02
【问题描述】:

我正在 Rails 控制台中编写以下内容。

> class Hello
>   def method
>     d = Jobs.find_by_sql("select id, count(*) as TOTAL from table group by id having count>100")
>     d.each do |m|
>         puts m.account_id
>       end
>     end
>   end

 => :method 
> Hello.method
ArgumentError: wrong number of arguments (0 for 1)

我无法弄清楚这段代码有什么问题。我该如何解决这个错误。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你的方法名“method”是Object类的现有方法,它最终被ruby中的所有类继承。

    您使用此名称定义一个实例方法,这很好,并且如果继承的实例方法已经存在,它将覆盖它。但是,当您调用它时,您将其称为 类方法(因为您在 Hello 上调用它,即类),因此您调用的是现有的"method" 方法,抱怨没有得到任何参数。

    你的方法更改为“foo”,然后尝试执行Hello.foo。您将收到“未定义的方法或变量”错误,因为没有 foo 类方法。

    那就做吧

    hello = Hello.new
    hello.foo
    

    它会起作用的。

    编辑:

    如果你想让它真正成为一个类方法,那么你可以通过以下任何一种方式来实现:

    class Hello
    
      def self.method
        d = Jobs.find_by_sql("select id, count(*) as TOTAL from table group by id having count>100")
        d.each do |m|
            puts m.account_id
          end
        end
      end
    
    end
    

    class Hello
    
      #class methods go in here 
      class << self
    
        def method
          d = Jobs.find_by_sql("select id, count(*) as TOTAL from table group by id having count>100")
          d.each do |m|
              puts m.account_id
            end
          end
        end
    
      end
    end
    

    顺便说一句,使用有意义的变量名是一种惯例,通常也是一个好主意。例如,如果您有一个变量是 Job 对象的集合,则将其称为“jobs”,而不是“d”。然后任何阅读您的代码的人都可以轻松记住该变量中保存的内容。

    使用这个原则,我会重写你的代码:

        def output_job_account_ids
          jobs = Jobs.find_by_sql("select id, count(*) as TOTAL from table group by id having count>100")
          jobs.each do |job|
              puts job.account_id
            end
          end
        end
    

    看到正在发生的事情如何变得更加明显?我也重命名了方法名:通常最好用方法名来描述方法的作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多