2017-04-23 130 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