我遇到了一個研究演練問題,我無法弄清楚。 下面是練習的鏈接。 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