ruby on rails - How to access first item in hash value array -
i have hash value 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 better when we're wasted", "it makes easier see"]}) real_world = song.new("real world" => ["straight want learn here", "if else fall apart"]) wasted.get_song_name() wasted.get_first_line() #=>i better when we're wasted #=>it makes easuer see
so when called wasted.get_first_line
, want first item in array of value. tried doing @lyrics.values[0]
, returns both lines of song instead of first one.
how accomplish this?
you need understand in above code @lyrics
hash. here doing , translates to:
@lyrics # => {"wasted"=>["i better when we're wasted", "it makes easier see"]} @lyrics.values # => [["i better when we're wasted", "it makes easier see"]] @lyrics.values[0] # => ["i better when we're wasted", "it makes easier see"] @lyrics.values[0][0] # => "i better when we're wasted"
therefore access first line, need first element of values array. i.e.
@lyrics.values[0][0]
or
@lyrics.values.first.first
Comments
Post a Comment