小编blo*_*lob的帖子

Ruby-初始化继承,仅具有某些参数的超级继承?

我最近一直在使用Ruby,但似乎找不到我的问题的答案。

我有一个班级和一个子班级。类具有某种initialize方法,子类具有其自己的initialize方法,该方法应该从中继承一些(但不是全部)变量,并将其自身的变量添加到子类对象中。

Person@name@age@occupation

Viking是应该有一个@name@age它从继承Person,另外一个@weaponPerson没有。一个Viking显然不需要任何东西@occupation,也不应该有一个。

# doesn't work
class Person
  def initialize(name, age, occupation)
    @name = name
    @age = age
    @occupation = occupation
  end
end

class Viking < Person
  def initialize(name, age, weapon)
    super(name, age) # this seems to cause error
    @weapon = weapon
  end
end

eric = Viking.new("Eric", 24, 'broadsword') 
# ArgError: …
Run Code Online (Sandbox Code Playgroud)

ruby inheritance initialization

3
推荐指数
2
解决办法
6786
查看次数

Ruby数组和nil guard

我有以下代码

class Room
  attr_reader :content, :descr
  def initialize
    @content     = get_content
    @descr       = get_description
  end

  def get_content
    ['errors', 'bugs', 'syntax problems'].sample
  end

  def get_description
    "This room has #{self.content}"
  end
end

@rooms = Array.new(3, Array.new(3))
@rooms[1][1] ||= Room.new 
# => #<Room:0x68985d8 @content="errors", @descr="This room has errors">

p @rooms # =>
#[[nil, #<Room:0x68985d8 @content="errors", @descr="This room has errors">, nil],
# [nil, #<Room:0x68985d8 @content="errors", @descr="This room has errors">, nil],
# [nil, #<Room:0x68985d8 @content="errors", @descr="This room has errors">, nil]]


@rooms = Array.new(3, Array.new(3))
@rooms[1][2] …
Run Code Online (Sandbox Code Playgroud)

ruby arrays multidimensional-array

0
推荐指数
1
解决办法
126
查看次数