无法添加到实例的哈希(ruby)

时间:2017-10-11 12:23:07

标签: ruby hash

我在使用#buy_fish添加到实例的#pets哈希时遇到问题。它成功返回了添加到哈希的内容,但哈希不会改变。

所有者类

class Owner
  attr_accessor :name

  def initialize(name)
    pets
  end

  def pets
    @pets = {cats: [], dogs: [], fishes: []}
  end

  def buy_fish(name)
    self.pets[:fishes] << Fish.new(name)
  end
end

鱼类

class Fish
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

2 个答案:

答案 0 :(得分:1)

正如Stefan所指出的,每次调用pets都会向@pets分配一个新哈希。在pets方法中添加||=修复此问题。

<强>代码

def pets
  @pets ||= {cats: [], dogs: [], fishes: []}
end

答案 1 :(得分:1)

@Matt的解决方案有效。

我只想补充一点,我认为class Owner attr_accessor :name attr_reader :pets def initialize(name) @pets = {cats: [], dogs: [], fishes: []} end def buy_fish(name) @pets[:fishes] << Fish.new(name) end end '评价在这里不应该是懒惰的原因。因此,您可以在构造函数中内联它并添加一个阅读器:

Dim time As DateTime
Dim deDE As New CultureInfo("de-DE") 'Since datumTbox.Text is German

If Date.TryParseExact(datumTbox.Text, "ddMMyy", deDE, DateTimeStyles.None, time) Then
    Console.WriteLine(time.ToString("dd/MM/yy"))
Else
    Console.WriteLine("The input is not in a ddMMyy format")
End If