6

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.

2

1 Answer 1

11

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}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.