質問

ように変換し、以下の文字列配列に/入れ子配列:

str = "[[this, is],[a, nested],[array]]"

newarray = # this is what I need help with!

newarray.inspect  # => [['this','is'],['a','nested'],['array']]
役に立ちましたか?

解決

しょうたいとYAML.

ものがありませんが、問題文字列になります。YAMLることが裏のスペース[ドメイン]を選択しますいる必要があります

str = "[[this, is], [a, nested], [array]]"

コード:

require 'yaml'
str = "[[this, is],[a, nested],[array]]"
### transform your string in a valid YAML-String
str.gsub!(/(\,)(\S)/, "\\1 \\2")
YAML::load(str)
# => [["this", "is"], ["a", "nested"], ["array"]]

他のヒント

のための笑顔で語ります:

 ary = eval("[[this, is],[a, nested],[array]]".gsub(/(\w+?)/, "'\\1'") )
 => [["this", "is"], ["a", "nested"], ["array"]]

免責事項:まないこと eval は、大変な思想もしていない商品については、有側の効果の例外の場合は入れ子にされた配列でない有効な

このままでしていただいているほとんど-JSON.の場合は文字列は文字のように、これは動作します:

JSON.parse(yourarray.gsub(/([a-z]+)/,'"\1"'))

できればい任意の文字以外の[],きい必要以:

JSON.parse("[[this, is],[a, nested],[array]]".gsub(/, /,",").gsub(/([^\[\]\,]+)/,'"\1"'))

のような基本的な構文解析作業です。一般的にアプローチにおいを再帰関数は以下のアルゴリズム

base case (input doesn't begin with '[') return the input
recursive case:
    split the input on ',' (you will need to find commas only at this level)
    for each sub string call this method again with the sub string
    return array containing the results from this recursive method

のslighlty難しい部分では分割された入力、シングル','.きく分けてこのようスキャンを通じての文字列は常にカウントのopenbrackets-closedbrakets見ています。その分割る場合はカンマ区切にはカウントがゼロに等しくなります。

を再帰的に機能する文字列の整数オフセット、および"を読み込み"は、配列になります。として返します配列または文字列ので、読みの整数オフセットを指後の配列の型になります。例えば:

s = "[[this, is],[a, nested],[array]]"

yourFunc(s, 1) # returns ['this', 'is'] and 11.
yourFunc(s, 2) # returns 'this' and 6.

そのままで別の機能を提供するオフセット0は、このオフセットの長さは文字列です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top