ruby - Raise Undefined local variable or method -
ok understand local variable , global variable, got exercise 40 on learnrubythehardway credit ask each method on hash.
$cities = {"ca" => "san francisco", "mi" => "detroit", "fl" => "jacksonville"} #adding new kay new value $cities["ny"] = "new york" $cities["or"] = "portland" def loop(map,state) $cities.each |map,state| if map.include? state return map[state] else return "not found." end end end $cities[:find] = method(:loop) while true print "state? (enter quit) " state = gets.chomp break if state.empty? #this line important ever! study! puts $cities[:find].call(cities,state) end
the error giving me undefined local variable or method 'cities'
anyway understand local variable can access in main file, when comes global variable, can assign $ , access method inside itself.
i have research on other undefined variable or method, theirs pretty straight forward.
this line problem:
puts $cities[:find].call(cities,state)
there no local variable cities
in scope, hence error.
to honest find whole example extremely contrived , pretty horrible. times needed global variables in last 10+ years of writing ruby can counted on fingers of 1 hand spare.
since seem confused global , local variables, have @ this:
$foo = "foo" defined?($foo) #=> "global-variable" defined?(foo) #=> nil
this what's happening in example $cities
, cities
(note missing $
).
Comments
Post a Comment