Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access first item in hash value array

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?

like image 559
James Mitchell Avatar asked Aug 16 '15 17:08

James Mitchell


1 Answers

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
like image 200
shivam Avatar answered Oct 03 '22 17:10

shivam