Reputation: 61
Is
class A < Struct.new(:att)
end
the same as
class A
attr_accessor :att
end
in Ruby?
Upvotes: 4
Views: 2390
Reputation: 48649
Why does a class inherit from a struct
It doesn't. Classes inherit from other classes. In ruby, to create an inheritance hierarchy you can write:
class A
def bark
puts "woof"
end
end
class B < A
end
B.new.bark
--output:--
woof
But, you can also do this:
class A
def bark
puts "woof"
end
end
def do_stuff
return A
end
class B < do_stuff
end
B.new.bark
--output:--
woof
Is that a class that inherits from a method? No! Ruby lets you use an arbitrary expression for the parent class--as long as it returns a class. The code:
Struct.new(:att)
is an arbitrary expression which returns a class:
x = Struct.new(:att)
p x
--output:--
#<Class:0x007f8c3126c568>
Upvotes: 0
Reputation: 198446
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
Upvotes: 11