Home > OS >  Lint/Syntax: class definition in method body Ruby
Lint/Syntax: class definition in method body Ruby

Time:08-12

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:

    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:

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
^^^

CodePudding user response:

From the docs;

There are three types of arguments when sending a message, the positional arguments, keyword (or named) arguments and the block argument. Each message sent may use one, two or all types of arguments, but the arguments must be supplied in this order.

So, in your example, the keyword argument name should be after the positional ones (age, specialization). 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

CodePudding user response:

You have to add in your .rubocop.yml file

AllCops:
  TargetRubyVersion: 3.1

and afterwards it will show more detailed rubocop errors of your code.

  • Related