Don't subclass Struct classes please by styx
instead of:
class Wheel < Struct.new(:rim, :tire)
#...
end
use
Wheel = Struct.new(:rim, :tire) do
# ...
end
instead of:
class Wheel < Struct.new(:rim, :tire)
#...
end
use
Wheel = Struct.new(:rim, :tire) do
# ...
end
Comments
releu commented 5 months ago
Why?
releu commented 5 months ago
one more unnecessary noname class?
makaroni4 commented 5 months ago
Agree, what is the profit?
ademidov commented 5 months ago
When subclassing from Struct.new(...), you actually do that:
Wheel = Class.new(Struct.new(...)), i.e. create two classes instead one and pollute ancestors chain with anonymous class:makaroni4 commented 5 months ago
@ademidov thanks a lot for explanation, great example!
robgleeson commented 5 months ago
Another reason is because you cannot use Kernel#load to re-load a file that creates a subclass of Struct (type mismatch, since your subclass already has a parent).
postmodern commented 5 months ago
Read the documentation for Struct.new
redjazz96 commented 5 months ago
@postmodern Struct.new allows for both versions, shown by the example:
postmodern commented 5 months ago
Also, what if you need to add additional methods to your Struct, but don't want to write all that boilerplate initialization code? Should we be using something like Values or Virtus instead?