Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classic hash to dot-notation hash

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.

like image 682
Oktav Avatar asked Dec 27 '22 00:12

Oktav


1 Answers

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}
like image 138
Dogbert Avatar answered Dec 28 '22 15:12

Dogbert