Ruby undefined variable in method body -


when run this, error stating city undefined. should do?

 def ticket_format    text = ""   tickets.each |price, artist|     if city == "chicago"       text += "#{artist} show cost #{price}"     else       text += "you paid #{price} see #{artist}"      end   end   text end 

the way city used, means it's whether local variable, i.e defined in function body, or method defined on same context ticket_format defined.

unlike procs , lambdas (or blocks in generale), methods in ruby not closures, i.e not keep context defined. if define city variable before method

  city = 'a ctiy'   def ticket_format       city == 'a city'      ...   end    # raise error 'undefined local variable or method "city"'   ticket_format 

so whether pass city argument, or define method city on same class ticket_format defined

 def city    @city   end   def ticket_format     if city == 'a city'     ...  end  

or

 def ticket_format city     if city == 'a city'     ...  end  

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -