1

我遇到了一个学习练习问题,我想不通。这是练习的链接。 https://learnrubythehardway.org/book/ex40.html

下面是我的作品。在 Study Drill 2 中,我传入了变量并且它起作用了。然而,在学习练习 3 中,我破坏了我的代码。我意识到我不是在传递变量,而是一个哈希值。而且因为我的课程接受 2 个参数,所以我不知道如何将字典作为 2 个参数传递。

class Song

  def initialize(lyrics, singer)
    @lyrics = lyrics
    @singer = singer
  end

  def sing_along()
    @lyrics.each {|line| puts line}
  end

    def singer_name()
    puts "The song is composed by #{@singer}"
  end

  def line_reader(lineNum)
    line = @lyrics[lineNum-1]
    puts "The lyrics line #{lineNum} is \"#{line}\"."
  end

end

# The lyrics are arrays, so they have [] brackets
practiceSing = Song.new(["This is line 1",
              "This is line 2",
              "This is line 3"],"PracticeBand")

practiceSing.sing_along()
practiceSing.singer_name()
practiceSing.line_reader(3)

puts "." * 20
puts "\n"

# Variable for passing. Working on dictionary to pass the singer value.
lovingThis = {["Don't know if I'm right",
              "but let's see if this works",
              "I hope it does"] => 'TestingBand'}

# Everything after this line is somewhat bugged
# Because I was using a variable as an argument
# I couldn't figure out how to use dictionary or function to work with 
this

practiceVariable = Song.new(lovingThis,lovingThis)

practiceVariable.sing_along()
practiceVariable.singer_name()
practiceVariable.line_reader(3)

这是输出。它应该做的是返回歌手/乐队,并返回请求的歌词行。

我是编码新手,请告知如何将哈希传递给类?如何将lovingThis 哈希传递给Song.new() 并读取为2 个参数?

4

1 回答 1

1

您可以像传递任何其他变量一样将哈希传递给类的构造函数,但是为此您需要更改构造函数定义以获取可变数量的参数,即def initialize(*args)

class Song
  def initialize(*args)
    if args[0].instance_of? Hash
      @lyrics = args[0].keys.first
      @singer = args[0].values.first
    else
      @lyrics = args[0]
      @singer = args[1]
    end
  end

  def sing_along()
    @lyrics.each {|line| puts line}
  end

  def singer_name()
    puts "The song is composed by #{@singer}"
  end

  def line_reader(lineNum)
    line = @lyrics[lineNum-1]
    puts "The lyrics line #{lineNum} is \"#{line}\"."
  end
end

# The lyrics are arrays, so they have [] brackets
practiceSing = Song.new(["This is line 1",
              "This is line 2",
              "This is line 3"],"PracticeBand")

practiceSing.sing_along()
practiceSing.singer_name()
practiceSing.line_reader(3)

puts "." * 20
puts "\n"

# Variable for passing. Working on dictionary to pass the singer value.
lovingThis = {["Don't know if I'm right",
              "but let's see if this works",
              "I hope it does"] => 'TestingBand'}

practiceVariable = Song.new(lovingThis)

practiceVariable.sing_along()
practiceVariable.singer_name()
practiceVariable.line_reader(3)
于 2017-04-23T19:54:25.480 回答