我有一个哈希值,它是一个歌词数组(第1行,第2行等)。
代码:
class Song
def initialize(lyrics)
@lyrics = lyrics
end
def get_song_name()
puts @lyrics.keys
end
def get_first_line()
puts @lyrics.values[0]
end
end
wasted = Song.new({"Wasted" => ["I like us better when we're wasted",
"It makes it easier to see"]})
real_world = Song.new("Real World" => ["Straight up what do you want to learn about here", "if i was someone else would this all fall apart"])
wasted.get_song_name()
wasted.get_first_line()
#=>I like us better when we're wasted
#=>It makes it easuer to see
所以当我调用wasted.get_first_line
时,我想让它获取值数组中的第一项。我尝试了@lyrics.values[0]
,但它返回了歌曲的两行而不是第一行。
我如何做到这一点?
答案 0 :(得分:7)
您需要了解在上面的代码中@lyrics
是一个哈希。以下是您正在做的事情以及它的翻译内容:
@lyrics
# => {"Wasted"=>["I like us better when we're wasted", "It makes it easier to see"]}
@lyrics.values
# => [["I like us better when we're wasted", "It makes it easier to see"]]
@lyrics.values[0]
# => ["I like us better when we're wasted", "It makes it easier to see"]
@lyrics.values[0][0]
# => "I like us better when we're wasted"
因此,要访问第一行,您需要获取values数组的第一个元素。即。
@lyrics.values[0][0]
或
@lyrics.values.first.first
答案 1 :(得分:3)
让我们使用这个哈希例如:
x = {foo: [:bar, :baz]}
x.values # => [[:bar, :baz]]
x.values.first # => [:bar, :baz]
x.values.first.first # => :bar
换句话说,@lyrics.values[0]
将返回@lyrics
哈希中的第一个值,这是两首歌曲的数组。你仍然需要从该阵列中获得第一首歌。
答案 2 :(得分:3)
这不是原始问题的答案,但如果我是你,我会修改下面的类。更容易将歌曲名称和歌词行存储为单独的属性,而不是将它们合并为哈希 - 这种方式违背了Song
类的全部目的。
class Song
attr_accessor :song_name, :lyrics
def initialize(song_name, lyrics)
@song_name = song_name
@lyrics = lyrics
end
end
请注意,您可能不需要get_first_line
方法。你总是可以使用Array#first
来产生同样的效果:
real_world = Song.new("Real World", ["Line 1", "Line 2"])
puts real_world.lyrics.first # Prints "Line 1"
您还可以使用数组索引
访问歌词行puts real_world.lyrics[1] # Prints "Line 2"