3

データベースに JSON 形式のハッシュがあります。例えば

{
  "one" => {
    "two" => {
      "three" => {}
    }
  } 
}

これを文字列から生成する必要があります。上記の例は、文字列「one.two.three」から生成されます。

まず、これをどのように行うのですか?

問題の後半。複数の文字列を受け取ります - それぞれが最後に構築されます。したがって、「one.two.three」、次に「one.two.four」を取得した場合、次のようにハッシュします。

{
  "one" => {
    "two" => {
      "three" => {},
      "four" => {}
    }
  } 
}

そして、「one.two.three」を 2 回取得した場合は、最新の「three」値でそこにあったものをオーバーライドする必要があります。文字列は任意の長さにすることもできます (例: "one.two.three.four.five" または単に "one")。うまくいけば、それは理にかなっていますか?

4

1 に答える 1

13

ネストされたハッシュを生成するには:

hash = {}

"one.two.three".split('.').reduce(hash) { |h,m| h[m] = {} }

puts hash #=> {"one"=>{"two"=>{"three"=>{}}}}

Rails がインストールされていない場合は、activesupport gem をインストールします。

gem install activesupport

次に、それをファイルに含めます。

require 'active_support/core_ext/hash/deep_merge'

hash = {
  "one" => {
    "two" => {
      "three" => {}
    }
  } 
}.deep_merge(another_hash)

内部へのアクセスは次のようになります。

hash['one']['two']['three'] #=> {}
于 2012-08-14T01:14:00.320 に答える