Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a class inherit from a struct

Tags:

ruby

Is

class A < Struct.new(:att)
end

the same as

class A
  attr_accessor :att
end

in Ruby?

like image 736
kravcneger Avatar asked Dec 24 '22 07:12

kravcneger


1 Answers

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
like image 75
Amadan Avatar answered Jan 12 '23 08:01

Amadan