From: "Jesús Gabriel y Galán" Date: 2012-01-10T05:08:43+09:00 Subject: Re: Class instance variable question On Mon, Jan 9, 2012 at 7:26 PM, Matt Mencel wrote: > 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. > > Thanks, > Matt > > > > > class Tools > >  @path = [] >  @all_values = {} > >  def self.get_all_values_nested(nested_hash={}) >    puts "ALL VALS: #{@all_values}" >    nested_hash.each_pair do |k,v| >      @path << k >      case v >        when Array, DateTime, FalseClass, Fixnum, NilClass, String, TrueClass then >          @all_values.merge!({"#{@path.join(".")}" => "#{v}"}) >          @path.pop >        when Hash then get_all_values_nested(v) >        else raise ArgumentError, "Unhandled type #{v.class}" >      end >    end >    @path.pop > >    return @all_values >  end > > end Instance variables keep their value after the method execution, that's why you are seeing that problem. Instead of using an instance variable you could just use the return value of the recursive call to merge it to a local variable that you then return. This way you won't need instance variables at all: require 'date' class Tools def self.get_all_values_nested(nested_hash={}, path=[]) all_values = {} nested_hash.each_pair do |k,v| path << k case v when Array, DateTime, FalseClass, Fixnum, NilClass, String, TrueClass then all_values.merge!({"#{path.join(".")}" => "#{v}"}) when Hash then all_values.merge!(get_all_values_nested(v, path)) else raise ArgumentError, "Unhandled type #{v.class}" end path.pop end return all_values end end p Tools.get_all_values_nested({"a" => 1, "b" => {:first => "1"}}) p Tools.get_all_values_nested({"a" => {"first_level" => 42, "nested" => {"key" => "value"}}, "b" => {:first => "1"}}) $ ruby nested_hash.rb {"a"=>"1", "b.first"=>"1"} {"a.first_level"=>"42", "a.nested.key"=>"value", "b.first"=>"1"} Does this help? Jesus.