私は勉強ドリルの問題に遭遇しましたが、私はそれを理解できませんでした。 ここに、練習問題へのリンクがあります。 https://learnrubythehardway.org/book/ex40.htmlRubyハッシュをクラスに渡す
以下は私の仕事です。 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です。それは歌手/バンドを返し、要求された歌詞ラインを返すことです。
私はコーディングが新しく、クラスにハッシュを渡す方法を教えてください。 lovingThisハッシュをSong.new()に渡して2つの引数として読み取るにはどうすればよいですか?
、すなわち配列になると予想されますか?そうであれば、キーが 'singer_name'で、値が歌詞行の配列であるハッシュ変数を作成できます。クラスに渡すとき:Song.new(some_hash ['singer_name']、some_hash.keys.first)。 – Anton