Can't access array defined outside my ruby function -
how can access array defined outside function? i've tried adding $coins.length had read somewhere global variable — didn't work. reason define array outside because there other functions below pushing new item same array.
coins = [] def start puts "it's sunny day. it's warm , feel great." puts "you've picked son creche. he's in mood , you've got home no problem." puts "this when troubles start, , know it." puts "you go out of elevator , before reach door... 'give me keeys'!" puts "do give him keys? (y/n)" print "> " while keys = gets.chomp.downcase case keys when "y" puts "you in, job. , coin" coins.push("1") puts "you have #{coins.length} coins" room when "n" cry("i wanted dooooooo iiiiiiiit!") else again end end end
ruby object oriented language. more, ruby appeared on scene motto “everything object.” numbers , (sic!) nil in ruby objects:
▶ 42.class #⇒ fixnum < integer ▶ nil.__id__ #⇒ 8 so, supposed use objects more complicated one-liner. objects have lot of goodness out of box: instance variables, lifecycle, etc.
class game def initialize @coins = [] end def add_coin(value) @coins << value end def coins @coins end def amount @coins.size end end now might create in instance of class , while it’s alive, hold value of @coins:
game = game.new game.add_coin("1") puts game.coins #⇒ ["1"] puts game.amount #⇒ 1 game.add_coin("1") game.add_coin("2") puts game.coins #⇒ ["1", "1", "2"] puts game.amount #⇒ 3
Comments
Post a Comment