gpt4 book ai didi

ruby-on-rails - rails 语法错误 : wrong number of arguments

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:20 25 4
gpt4 key购买 nike

在用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​​ 中运行了相同的代码,它在没有空格的情况下工作正常。好好奇!

最佳答案

您可以 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 是一个属性 getter(我猜是吧?)并且不接受任何参数,你会得到一个 ArgumentError


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

  • :调用
  • subject(调用方法的值,nil if 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)
^

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

关于ruby-on-rails - rails 语法错误 : wrong number of arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com