Is there a simple way in Ruby 2/Rails 3 to transform this:
{a: {b: {"1" => 1, "2" => 2}, d: "Something"}, b: {c: 1}}
into this:
{"a.b.1" => 1, "a.b.2" => 2, "a.d" => "Something", "b.c" => 1}
I'm not talking about this precise hash but transform any hash into a dot-notation hash.
Here's the cleanest solution I could come up with right now:
def dot_it(object, prefix = nil)
if object.is_a? Hash
object.map do |key, value|
if prefix
dot_it value, "#{prefix}.#{key}"
else
dot_it value, "#{key}"
end
end.reduce(&:merge)
else
{prefix => object}
end
end
Test:
input = {a: {b: {"1" => 1, "2" => 2}, d: "Something"}, b: {c: 1}}
p dot_it input
Output:
{"a.b.1"=>1, "a.b.2"=>2, "a.d"=>"Something", "b.c"=>1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With