将Ruby Hash传递给类

时间:2017-04-23 19:21:54

标签: ruby class ruby-hash

我遇到了一个研究训练问题,我无法弄明白。 这是练习的链接。 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)

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

我是编码的新手,请告知如何将哈希传递给课程? 如何将loveThis哈希传递给Song.new()并读作2个参数?

1 个答案:

答案 0 :(得分:1)

你可以像传递任何其他变量一样将哈希传递给类的构造函数,但是为此你需要改变构造函数定义以获取可变数量的参数,即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)

<marker id="arrowend" viewBox="0 0 13 10" refX="2" refY="5" markerWidth="3.5" markerHeight="3.5" orient="auto">
    <path d="M 0 0  C 0 0, 3 5, 0 10   L 0 10  L 13 5" fill="red"/>
</marker>

<marker id="arrowstart" viewBox="0 0 -13 -10" refX="-2" refY="-5" markerWidth="-3.5" markerHeight="-3.5" orient="auto">
    <path d="M 0 0  C 0 0, -3 -5, 0 -10   L 0 -10  L -13 -5" fill="red"/>
</marker>