Robert said:
2010/2/24 Xavier Noria said:
{'en' =3D> {'A' =3D> Fixnum, 'B' =3D> {'C' =3D> Fixnum, 'D' =3D> Strin= g }}
=EF=BF=BD =EF=BF=BDnewh[k] =3D v.is_a?(Hash) ? classify_values(v) : v.c= lass
=EF=BF=BDend
=EF=BF=BDnewh
end
p classify_values({'en' =3D> {'A' =3D> 1, 'B' =3D> {'C' =3D> 3, 'D' =3D=
'four' }}})
I would do it a tad differently:
def classify(o)
=C2=A0 case o
=C2=A0 when Hash
=C2=A0 =C2=A0 h =3D {}
=C2=A0 =C2=A0 o.each {|k,v| h[k] =3D classify(v)}
=C2=A0 =C2=A0 h
=C2=A0 else
=C2=A0 =C2=A0 o.class
=C2=A0 end
end
Advantage is that you can stuff anything in the method while your
variant requires the argument to be a Hash. =C2=A0The difference may see= m
subtle but if you add more collection types for special treatment,
you'll will notice a difference in effort to implement it. =C2=A0I can
simply do
def classify(o)
=C2=A0 case o
=C2=A0 when Hash
=C2=A0 =C2=A0 h =3D {}
=C2=A0 =C2=A0 o.each {|k,v| h[k] =3D classify(v)}
=C2=A0 =C2=A0 h
=C2=A0 when Array
=C2=A0 =C2=A0 o.map {|v| classify(v)}
=C2=A0 else
=C2=A0 =C2=A0 o.class
=C2=A0 end
end
while you need to do a more complicated code change.
Kind regards
robert
Thanks, this is very helpful.
I am trying to adapt this a bit, but with no luck so far.
What I'd like to do is to start with a hash and have the above code be
additive.
In other words, if I have the following code:
h0 =3D {}
h1 =3D {'en' =3D> {'A' =3D> 5, 'B' =3D> { 'C' =3D> 'xxx', 'D' =3D> { 'E' = =3D> 4 }}}}
h2 =3D {'en' =3D> {'F' =3D> 'yyy'}}
I'd like to be able to call the classify method like this:
puts h0.classify(h1).classify(h2).inspect
And get the following result:
{'en' =3D> {'A' =3D> Fixnum, 'B' =3D> { 'C' =3D> String, 'D' =3D> { 'E' = =3D> Fixnum
}}, 'F' =3D> String }}
So I figured it would be something like this:
class Hash
=C2=A0def classify(o)
=C2=A0 =C2=A0case o
=C2=A0 =C2=A0when Hash
=C2=A0 =C2=A0 =C2=A0h =3D self
=C2=A0 =C2=A0 =C2=A0o.each {|k,v| h[k] =3D classify(v)}
=C2=A0 =C2=A0 =C2=A0h
=C2=A0 =C2=A0when Array
=C2=A0 =C2=A0 =C2=A0o.map {|v| classify(v)}
=C2=A0 =C2=A0else
=C2=A0 =C2=A0 =C2=A0o.class
=C2=A0 =C2=A0end
=C2=A0end
end
But this is probably wrong in a few ways. =C2=A0Any suggestions would be
appreciated.