376dc89f458bb3b9ac3fd4d559098645

there has got to be a better way...

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 !

7c45f63f61e478233f0c2ad3006b178c

michiel

October 5, 2007, October 05, 2007 09:31, permalink

1 rating. Login to rate!

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
Avatar

tneumann

October 5, 2007, October 05, 2007 15:43, permalink

No rating. Login to rate!

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
Avatar

tneumann

October 5, 2007, October 05, 2007 15:51, permalink

No rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel