Is
class A < Struct.new(:att)
end
the same as
class A
attr_accessor :att
end
in Ruby?
No. It is equal to
B = Struct.new(:att)
class A < B; end
which is pretty much equivalent, but not equal to
class B
attr_accesor :att
def initialize(att)
@att = att
end
end
class A < B
end
Not equal because the value is not actually stored in @att
:
B = Struct.new(:att)
class B
def real_att
@att
end
end
b = B.new(32)
b.att
# => 32
b.real_att
# => nil
Personally, I don't see why one wouldn't just do A = Struct.new(:att)
, without the inheritance business.
EDIT: As Jordan notes in comments, there is an even nicer way to add methods to a struct: the Struct
conStructor (teehee) takes a block, which executes in the context of the newly created class: whatever you define there, will be defined on the new struct.
B = Struct.new(:att) do
def process
#...
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With