Ruby 每个块的多维阵列
我试图遍历名为playlist的多维数组来计算播放列表的总持续时间。但是,我继续收到错误“block in duration”:未定义的方法“[]”,用于 错误发生在list.rb的第31行 Song.rbRuby 每个块的多维阵列,ruby,Ruby,我试图遍历名为playlist的多维数组来计算播放列表的总持续时间。但是,我继续收到错误“block in duration”:未定义的方法“[]”,用于 错误发生在list.rb的第31行 Song.rb class Song attr_accessor :name, :artist, :duration, :lyrics def initialize(name, artist, duration, lyrics) @name = name @artist = art
class Song
attr_accessor :name, :artist, :duration, :lyrics
def initialize(name, artist, duration, lyrics)
@name = name
@artist = artist
@duration = duration #duration in seconds
@lyrics = lyrics
end
def play_song
#`say #{lyrics}`
puts "#{lyrics}"
end
def friendly_duration
puts "#{(duration / 60).to_i}" + ":" "#{(duration % 60).to_i}"
end
end
List.rb
class List
attr_reader :songs
def initialize
@songs = []
end
def add_song(song)
@songs << song
end
def play
songs.each do |song|
puts song.lyrics
end
end
def shuffle
songs.shuffle.each do |song|
puts song.lyrics
end
end
def duration
sum = 0
songs.each do |song|
sum += song.duration
end
puts "#{(sum / 60).to_i}" + ":" "#{(sum % 60).to_i}"
end
end
我会成功的
def duration
songs.map{|s| s[2]}.reduce(:+)
end
songs.map{124; s|s[2}
将给出您的[200248192]
,然后当您调用时,它将执行200+248+192
并返回总和
@playlist = [
["Levels", "Avicii", 200, "Ooooo sometimes I get a good feeling..."],
["Poison", "Martin Garrix", 248, "Beep boop boop boop beep beep"],
["Animals", "Martin Garrix", 192, "We are f*ckin animals.."]
]
def duration
sum = 0
@playlist.each do |song| # playlist is a local variable and not visible inside a method,
# which has its own scope. @playlist however is visible
sum += song[2]
end
"#{(sum / 60).to_i}" + ":" "#{(sum % 60).to_i}" #no puts, because puts returns nil,
# which is strange for a method called duration
end
puts duration
考虑对@playlist
的元素进行哈希:
@playlist = [
{ :name=>"Levels", :artist=>"Avicii", :duration=>200,
:lyrics=>"Ooooo sometimes I get a good feeling..." },
{ :name=>"Poison", :artist=>"Martin Garrix", :duration=>248,
:lyrics=>"Beep boop boop boop beep beep" },
{ :name=>"Animals", :artist=>"Martin Garrix", :duration=>192,
:lyrics=>"We are well-bahaved animals.."}
]
@playlist.reduce(0) { |tot,h| tot + h[:duration] }
#=> 640
这只是代码的一个片段,但希望足够。如果需要更多信息,请告诉我。请在代码中包含错误行号。我找到了错误行号,并用解决方案更新了代码。这是有意义的,应该可以工作,但我似乎遇到了相同的错误。我想我的类中可能有其他错误。
@playlist = [
["Levels", "Avicii", 200, "Ooooo sometimes I get a good feeling..."],
["Poison", "Martin Garrix", 248, "Beep boop boop boop beep beep"],
["Animals", "Martin Garrix", 192, "We are well-bahaved animals.."]
@playlist.transpose[2].reduce(:+)
#=> 640
@playlist = [
{ :name=>"Levels", :artist=>"Avicii", :duration=>200,
:lyrics=>"Ooooo sometimes I get a good feeling..." },
{ :name=>"Poison", :artist=>"Martin Garrix", :duration=>248,
:lyrics=>"Beep boop boop boop beep beep" },
{ :name=>"Animals", :artist=>"Martin Garrix", :duration=>192,
:lyrics=>"We are well-bahaved animals.."}
]
@playlist.reduce(0) { |tot,h| tot + h[:duration] }
#=> 640