Class and inheritance

I am trying to understand the inheritance system in Ruby. This is my code:

class Man
  attr_accessor :name

  def initialize(name = "Foo")
    @name = name
  end
end

class User < Man
  attr_accessor :mail

  def initialize(mail = "bar")
    super
    @mail = mail
  end
end

And this is my test:

man = Man.new
man
=> #<Man:0x007fb68da4a768 @name="Foo">

user = User.new
user
=> #<User:0x007fb68da442c8 @name="bar", @mail="bar">

I do not understand why user @name is not "Foo"! Normal, it should, because this is the default argument in the human initialization method, no?

Thank you for your help!

+4
source share
5 answers

super(without a list of arguments) calls the same method in the superclass with the same arguments that were passed. If you want to explicitly pass any arguments, you must use an empty list of arguments super().

: super , . . foo foo() , . super : super() , super .

: , initialize, ... ? , , super , .

+3

super - , . "" ( "" ).

, :

class User < Man
  attr_accessor :mail

  def initialize(name = "foo", mail = "bar")
    super(name)
    @mail = mail
  end
end
+2

User , parrameter bcs. super, .

super(), parrameters bcs, Parent initial method .

class Man
  attr_accessor :name

  def initialize(name = "Foo")
    @name = name
  end
end

class User < Man
  attr_accessor :mail

  def initialize(mail = "bar")
    super()
    @mail = mail
  end
end

Man.new
# => #<Man:0x52a7e380 @name="Foo">
User.new
# => #<User:0x11777eb0 @mail="bar", @name="Foo">
0

, :

class Man
  attr_accessor :name

  def initialize(name = "Foo")
    @name = name
  end
end

class User < Man
  attr_accessor :mail

  def initialize(mail = "bar")
    super()
    @mail = mail
  end
end

man = Man.new
puts man.name  #> Foo
user = User.new
puts user.name  #> Foo
0

super , , . , , .

:

def initialize(mail = "bar")
  super()
  @mail = mail
end

, , .

0
source

All Articles