【问题标题】:rails syntax error: wrong number of argumentsrails语法错误:参数数量错误
【发布时间】:2018-07-29 03:35:27
【问题描述】:

在用rails建网站的时候,我发现了一个小语法错误,我真的不明白是什么原因造成的。

 class User < ApplicationRecord
   has_secure_password
   has_many :posts, dependent: :nullify
   has_many :comments, dependent: :nullify

   validates :first_name, :last_name, presence: true, length: {maximum: 30}
   validates :email, presence: true, uniqueness: true, format: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i


   def full_name
     (first_name +" "+ last_name).titleize
   end

 end

这是用户的模型文件。如果我运行此文件,则会导致错误:参数数量错误(给定 1,预期为 0)。但是,如果我给这样一个空间,

  def full_name
     (first_name + " "+ last_name).titleize
   end

正常运行。

虽然我知道我可以忽略它,但我只是很好奇空格如何导致参数错误,我认为这不是没有参数..

我还通过在字符串类中创建自己的 titleize 方法在普通 ruby​​ 中运行相同的代码,它在没有空格的情况下工作正常。 好好奇!

【问题讨论】:

    标签: ruby-on-rails ruby methods syntax arguments


    【解决方案1】:

    您可以use ruby_parser 来消除您对实际解析方式的疑虑。

    RubyParser.for_current_ruby.parse '(first_name +" "+ last_name)' 结果:

    s(:call, nil,
             :first_name,
             s(:call, s(:call, s(:str, " "),
                               :+@),
                      :+,
                      s(:call, nil,
                               :last_name)))
    

    实际上,你得到的是first_name((+" ") + last_name),或者以一种更冗余/有条理的方式,self.first_name((" ".+@).+(self.last_name))。

    意思是在first_name 方法的调用中有一个参数,源于在" " 上意外使用了+@,一元加号。但是由于first_name 是一个属性获取器(我猜?)并且不接受任何参数,所以你得到一个ArgumentError。


    为了帮助您解释此输出,:call S 表达式包含:

    • :call
    • 主题(调用方法的值,nil 如果self)
    • 方法名作为符号
    • 0 个或多个参数

    顺便说一句,Rubocop 可能已经警告过你:

    Lint/AmbiguousOperator: Ambiguous positive number operator. Parenthesize the method
    arguments if it's surely a positive number operator, or add a whitespace to the
    right of the + if it should be a addition.
    (first_name +" "+ last_name)
                ^
    

    考虑将其添加到您的工作流程中。

    【讨论】:

    • 哦,TIL ruby_parser - 太棒了!
    • 非常感谢您的详细解释!我尊重你的知识
    【解决方案2】:

    当您将代码直接放在它旁边时,这可能在一元加运算符和二元加运算符之间进行。

    一元加号就像一元减号,例如-2,我相信你明白写1 -2和1 - 2之间的区别吗?

    顺便说一句,标准的“ruby 方式”是插值而不是使用连接,所以你的行会更好写:

    "#{first_name} #{last_name}".titleize
    

    【讨论】:

      猜你喜欢
      • 2014-05-28
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多