我遇到了一个研究演练问题,我无法弄清楚。 下面是练习的链接。 https://learnrubythehardway.org/book/ex40.html将红宝石哈希传入类
以下是我的工作。在学习钻2,我通过了变量,它的工作。 但是,在学习演习3中,我弄坏了我的代码。我意识到我没有传递变量,而是散列。因为我的课程有两个参数,所以我无法弄清楚如何将字典作为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。它应该做的是返回歌手/乐队,并返回请求的歌词行。
我是新来的编码,请告知如何将哈希值传入类? 如何将这个散列传递给Song.new()并将其读为2个参数?
你的歌词伊娃预计会是一个数组?如果是这样,你可以创建哈希变量,其中的关键是一个'singer_name',而一个值是一个歌词行的数组。传递给课程时使用:Song.new(some_hash ['singer_name'],some_hash.keys.first)。 – Anton