From: Matt Mencel Date: 2012-01-10T05:05:21+09:00 Subject: Re: Class instance variable question Possible workaround. Since @path is popped clean each time it's used I think I can leave that outside the method and put @all_values inside the method. It's an ugly hack but I think it works for now until I figure out a better way to do it. Definitely open to suggestions. Thanks, Matt ----- Original Message ----- From: "Matt Mencel" To: "ruby-talk ML" Sent: Monday, January 9, 2012 1:38:15 PM Subject: Re: Class instance variable question Tried that, and it works to point except I lose the pertinent @path data I need. So if the vars are outside the method then the returned hash looks like this... { "department.org_unit_id.id" => "6830", "department.name" => "Art", "department.code" => "08", "department.path" => "/content/Art" } ...if I put the vars inside the method I lose the identifying path information... { "id" => "6830", "name" => "Art", "code" => "08", "path" => "/content/Art" } A conundrum.... In case you are curious, I'm using this in a ruby gem I created to interface with Desire2Learn SOAP stuff. I use the Savon gem to grab the SOAP responses....and the responses are nested hashes.....and I sometimes need to know the nested path into the hash value I'm looking for. https://github.com/chewie71/ruby-d2l Matt ----- Original Message ----- From: "Stefano Crocco" To: "ruby-talk ML" Sent: Monday, January 9, 2012 12:46:24 PM Subject: Re: Class instance variable question Il giorno Tue, 10 Jan 2012 03:26:19 +0900 Matt Mencel ha scritto: > Hi, > > I have this class (below) that takes a deeply nested hash and returns back > a new hash without all the nesting. The problem I'm having is that it > seems to be that @all_values is not empty if I call it a second time from > my program. First time is fine, but the next time I use > get_all_values_nested, @all_values still has the results in it from the > first time it was used. > > Any thoughts on what I'm doing wrong? I just want @path and @all_values to > be empty each time I use the get_all_values_nested function. By definition, instance variables (including instance variables of class objects) keep their values until something else is assigned to them. If you need to access the values stored in @path and @all_values from somewhere other than gel_all_values_nested, but you want them empty in that method, then you'll have to do so yourself: class Tools def self.get_all_values_nested nested_hash = {} @path = [] @all_values = {} # ... end end If those two variables are only needed from within the body of get_all_values_nested, then you should use local variables instead. I hope this helps Stefano