简体   繁体   English

lint/语法:方法体 Ruby 中的 class 定义

[英]Lint/Syntax: class definition in method body Ruby

Please I have installed Ruby 3.1.2 and using rubocop 1.34.1 (using Parser 3.1.2.1, rubocop-ast 1.21.0, running on ruby 3.1.2 x86_64-linux) My code is:请我安装 Ruby 3.1.2 并使用 rubocop 1.34.1(使用 Parser 3.1.2.1,rubocop-ast 1.21.0,在 ruby 3.1.2 x86_64-linux 上运行)我的代码是:

    require "./person.rb"

class Teacher < Person

  def initialize(name: "Unknow", age, specialization)
    super(name, age)
    @specialization = specialization
  end

  def can_use_services?
    true
  end
end

And when I run rubocop it shows the following offenses:当我运行 rubocop 时,它会显示以下违规行为:

classes/teacher.rb:3:1: E: Lint/Syntax: class definition in method body
(Using Ruby 3.2 parser; configure using TargetRubyVersion parameter, under AllCops)
class Teacher < Person
^^^^^
classes/teacher.rb:5:34: E: Lint/Syntax: unexpected token tIDENTIFIER
(Using Ruby 3.2 parser; configure using TargetRubyVersion parameter, under AllCops)
  def initialize(name: "Unknow", age, specialization)
                                 ^^^
classes/teacher.rb:5:53: E: Lint/Syntax: unexpected token tRPAREN
(Using Ruby 3.2 parser; configure using TargetRubyVersion parameter, under AllCops)
  def initialize(name: "Unknow", age, specialization)
                                                    ^
classes/teacher.rb:13:1: E: Lint/Syntax: unexpected token kEND
(Using Ruby 3.2 parser; configure using TargetRubyVersion parameter, under AllCops)
end
^^^

From the docs ;来自文档

There are three types of arguments when sending a message, the positional arguments, keyword (or named) arguments and the block argument.发送消息时存在三种类型的 arguments,位置 arguments,关键字(或命名)arguments 和块参数。 Each message sent may use one, two or all types of arguments, but the arguments must be supplied in this order.发送的每条消息可以使用一种、两种或所有类型的 arguments,但必须按此顺序提供 arguments。

So, in your example, the keyword argument name should be after the positional ones ( age , specialization ).因此,在您的示例中,关键字参数name应位于位置参数名称( agespecialization )之后。 If you move it at the end then it should work.如果你在最后移动它,那么它应该可以工作。

class Teacher < Person
  def initialize(age, specialization, name: "Unknow")
    super(name, age)
    @specialization = specialization
  end

  ...
end

You have to add in your .rubocop.yml file您必须添加.rubocop.yml文件

AllCops:
  TargetRubyVersion: 3.1

and afterwards it will show more detailed rubocop errors of your code.之后它将显示您代码的更详细的 rubocop 错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM