1 2 3 4 5 6 7 8 9 10 11
# Converts: # {:hash => [{:foo => 1}, {:foo => 2}]} # # To: # {:hash => [{:foo => "1"}, {:foo => "2"}]} a[:hash].each do |i| i.each do |key,value| a[:hash][a[:hash].index(i)][key] = value.to_s end end
Refactorings
No refactoring yet !
michiel
October 5, 2007, October 05, 2007 09:31, permalink
In your inner loop, i == a[:hash][a[:hash].index(i)].
1 2 3 4 5 6 7 8 9 10 11
# Converts: # {:hash => [{:foo => 1}, {:foo => 2}]} # # To: # {:hash => [{:foo => "1"}, {:foo => "2"}]} a[:hash].each do |i| i.each do |key,value| i[key] = value.to_s end end
tneumann
October 5, 2007, October 05, 2007 15:43, permalink
you may want something more general here:
1 2 3 4 5 6 7
def stringify_values(x) case x when Hash: x.each_pair {|k,v| x[k] = stringify_values(v) } when Array: x.map {|a| stringify_values(a)} else x.to_s end end
tneumann
October 5, 2007, October 05, 2007 15:51, permalink
oh I just realize that that code does modify hashes in-place, but arrays not. let's make 2 versions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# in-place version - modifies x def stringify_values!(x) case x when Hash: x.each_pair {|k,v| x[k] = stringify_values(v) } when Enumerable: x.map! {|a| stringify_values(a)} else x.to_s end end # does not modify x, generates new arrays/hashes def stringify_values(x) case x when Hash: x.inject({}) {|m,(k,v)| m[k] = stringify_values(v); m } when Enumerable: x.map {|a| stringify_values(a)} else x.to_s end end
there has got to be a better way...