1, "2" => 2}, d: "Something"}, b: {c: 1}}...">

Classic hash for dot notation

Is there an easy way in Ruby 2 / Rails 3 to convert this:

{a: {b: {"1" => 1, "2" => 2}, d: "Something"}, b: {c: 1}} 

in it:

 {"ab1" => 1, "ab2" => 2, "ad" => "Something", "bc" => 1} 

I'm not talking about this exact hash, but will convert any hash into a hash representation of the point.

+4
source share
1 answer

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:

 {"ab1"=>1, "ab2"=>2, "ad"=>"Something", "bc"=>1} 
+9
source

Source: https://habr.com/ru/post/1489520/


All Articles