次のハッシュの配列があります。
[
{"type"=>"paragaph", "class"=>"red", "content"=>"[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]"},
{"type"=>"image", "class"=>"grid", "content"=>"[id:1|title:image1][id:2|title:image2][id:3|title:image3]"}
]
角かっこを含むハッシュ値を値の配列に変換しようとしています。これはまったく問題ありません。問題は、角かっこを含まない他のすべてのハッシュ値を破棄することです。
pipe_regex = /\|\s*(?=[^\[\]]*(?:\[|$))/
colon_regex = /\:\s*(?=[^\[\]]*(?:\[|$))/
array_hash.map {|m| m.update(m) {|k,v| v.scan(/\[(.*?)\]/).map {|m| m[0].split(pipe_regex)}.map {|m| m.map {|n| n.split(colon_regex)}}}}
少し面倒ですが、上記のコードは各ハッシュ値を見つけて「[]」文字に基づいて分割しますが、「[]」がなければすべてを破壊するようにも見えます。次に、'|' でそれらを分割します。次に、「:」を分割します。これは完全に正常に機能しているように見えます。
次に、値をハッシュに変換して、元の角括弧を含むものがハッシュの配列になるようにします。
array_hash.map {|m| m.update(m) {|k,v| v.map {|n| Hash[n]}}}
これもうまくいきそうです。すべての最終結果は次のように照合されます。
[
{"type"=>[], "class"=>[], "content"=>[{"class"=>"intro", "body"=>"This is the introduction paragraph."}, {"body"=>"This is the second paragraph."}]},
{"type"=>[], "class"=>[], "content"=>[{"id"=>"1", "title"=>"image1"}, {"id"=>"2", "title"=>"image2"}, {"id"=>"3", "title"=>"image3"}]}
]
.scan(/\[(.*?)\]/)
「[]」を含む文字列にのみ適用するにはどうすればよいですか? これが結果です。
[
{"type"=>"paragraph", "class"=>"red", "content"=>[{"class"=>"intro", "body"=>"This is the introduction paragraph."}, {"body"=>"This is the second paragraph."}]},
{"type"=>"image", "class"=>"grid", "content"=>[{"id"=>"1", "title"=>"image1"}, {"id"=>"2", "title"=>"image2"}, {"id"=>"3", "title"=>"image3"}]}
]