2017-04-23 98 views
1

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

+0

你的歌詞伊娃預計會是一個數組?如果是這樣,你可以創建哈希變量,其中的關鍵是一個'singer_name',而一個值是一個歌詞行的數組。傳遞給課程時使用:Song.new(some_hash ['singer_name'],some_hash.keys.first)。 – Anton

回答

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) 
+0

非常感謝,我從來沒有想過要改變 接受的論點數量。我一直試圖通過更改散列來獲取2個參數,或者創建返回2個參數的函數。 這完美的作品! – Joey