4

Ruby 2/Rails 3 中是否有一种简单的方法来转换它:

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

进入这个:

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

我不是在谈论这个精确的散列,而是将任何散列转换为点符号散列。

4

1 回答 1

10

这是我现在能想到的最干净的解决方案:

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

测试:

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

p dot_it input

输出:

{"a.b.1"=>1, "a.b.2"=>2, "a.d"=>"Something", "b.c"=>1}
于 2013-07-03T15:27:59.273 回答