I have a hash whose value is an array of song lyrics (line1, line2, etc..)
Code:
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
So when I called wasted.get_first_line
, I want it to get the first item in the array of the value. I tried doing @lyrics.values[0]
, but it returns both lines of the song instead of the first one.
How do I accomplish this?
You need to understand that in the above code @lyrics
is a Hash. Here is what you are doing and what it translates to:
@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"
Therefore to access the first line, you need to get the first element of the values array. i.e.
@lyrics.values[0][0]
or
@lyrics.values.first.first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With