rubocop / rubocop/ruby-style-guide

`X = Struct.new(:x) do` is bad

Open
#744 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Approved
Dominant language
No language data
Stars
16.5k
Forks
3.3k
PR merge metrics
No merged PRs in 30d

Description

The style guide suggest to use

X = Struct.new(:x) do
  def method
  end
end

# instead of

class Y < Struct.new(:y)
  def method
  end
end

I think this is a bad recommendation. Yes, the later creates an unnecessary anonymous class, but it uses the usual syntax to create classes and thus is easy to understand. Even Rubocop doesn't recognize the assignment syntax everywhere (E.g. Style/Documentation doesn't care about this).

Also, this leads to hard to understand errors:

X = Struct.new(:x) do
  XX = true
end

defined?(X::XX) # => nil
defined?(XX) # => "constant"

class Y < Struct.new(:y)
  YY = true
end

defined?(Y::YY) # => "constant"
defined?(YY) # => nil

This is possible, but is it better?

Z = Struct.new(:z)
class Z
  ZZ = true
end

defined?(Z::ZZ) # => "constant"
defined?(ZZ) # => nil

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Review the style guide recommendation about assigning Struct.new and compare it with the alternative class syntax and the Style/Documentation behavior cited in the issue. Decide whether the recommendation should change, and document the chosen guidance with examples that make constant behavior and readability clear.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.