From: Brian Candler Date: 2008-10-21T16:59:51+09:00 Subject: Re: Can anyone tell me why my code isn't working? Adam Penny wrote: > For some reason the get_mac_by_printer(host_name) method isn't working. > All the other bits work, but I have a feeling that I'm running into a > problem with variables defined within blocks, but I'm at a loss as to > how to negotiate it. No, nothing to do with variable scoping. > The resulting mac is returning as nilClass and it > definitely isn't nil! Code as follows: ... > def get_mac_by_host(host_name) > servers=@plist_hash['servers'].each do |s| > mac=s['mac'] if s['name']==host_name > return mac > end > end It definitely *is* nil. Note that your 'each' loop will onlyever run for one iteration, since 'return mac' will always return from the enclosing method (get_mac_by_host) during the first iteration. So, unless the passed host_name happens to match the first entry of @plist_hash['servers'], then the assignment mac = s['mac'] if s['name']==host_name will not be executed (because it's qualified by "if ... false condition ..."), so the value of the local variable 'mac' will be nil. To demonstrate: if 1 == 2 foo = "oops" end puts foo # nil So your loop is similar to: def mycode (1..5).each do |v| res = v if v == 3 return res end end puts mycode # nil You could fix this by changin "return res" to "return res if v == 3", or "return res if res", but more simply def mycode (1..5).each do |v| return v if v == 3 end end puts mycode # 3 -- Posted via http://www.ruby-forum.com/.