使用Class实例化我的Song类

时间:2013-10-22 22:03:07

标签: ruby class instantiation class-variables

我正在通过学​​习Ruby的艰辛之路 - ex40

目前,代码工作正常。那不是我的问题。我的问题是每次添加新歌。 A)我需要在initialize方法中创建一个实例变量。 B)然后,我必须给它一个attr_reader。

我知道的是否可以A)不必继续创建新的实例变量,而只需要在Song类中创建变量。 B)不必为每个变量创建一个attr_reader。

class Song
  def initialize()
    @jcole_lighter = "Come here, I\'m about to take you higher"
    @hold_on_drake = ["Cause you\'re a good girl and you know it",
                          "You act so different around me",
                          "Cause you\'re a good girl and you know it"]
  end


  def sing_me_a_song()
        for line in initialize
            puts line
        end
    end

  attr_reader :jcole_lighter
  attr_reader :hold_on_drake

end


thing = Song.new
puts thing.jcole_lighter()
puts "-"*10
thing= Song.new
puts thing.hold_on_drake()

1 个答案:

答案 0 :(得分:1)

检查this以获取对attr_readerattr_writerattr_accessor的详细解释。

并检查this以了解如何向构造函数添加参数。

您可以在:attr_accessor :artistsSonginitialize内执行此操作:

@artists = Array.new

然后你可以有一个方法add

def add(artist)
  @artists << artist
end

只是一个想法。很乐意帮助德雷克球迷。

相关问题