Hi Jesus,
I tried your suggestion…
class Tools
def self.get_all_values_nested(nested_hash={})
@all_values = _get_all_values_nested(nested_hash)
end
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
…and it seems to work nicely. The all_values hash is cleared each
time, but values in path are sent in each time the
_get_all_values_nested is recursively called. I’ll see how it goes with
further testing.
Thanks!
Matt
----- Original Message -----
From: “Jesús Gabriel y Galán” [email protected]
To: “ruby-talk ML” [email protected]
Sent: Monday, January 9, 2012 2:14:37 PM
Subject: Re: Class instance variable question
On Mon, Jan 9, 2012 at 7:46 PM, Stefano C. [email protected]
wrote:
first time it was used.
class Tools
def self.get_all_values_nested nested_hash = {}
@path = []
@all_values = {}
…
end
end
The problem there is that you lose the aggregation of path within the
recursive calls, since you are clearing at the beggining of each call.
If those two variables are only needed from within the body of
get_all_values_nested, then you should use local variables instead.
That’s what I thought. If this is not the case, then the solution
should be different, but I’m not sure how those two requirements hold
up together: you need them empty before calling that method, but need
to read the resulting values in other cases. Also, I think path ends
up empty after the call, so maybe we are talking only about
all_values. If this is the case I would do it like this:
class Tools
def self.get_all_values_nested(nested_hash={})
@all_values = _get_all_values_nested(nested_hash)
end
end
and use the definition for _get_all_values_nested that I propose in my
other email. The OP should clarify, but I don’t think his use case
involves having memory of the computation within calls or something
like that.
Jesus.