如何将带括号的Ruby字符串转换为数组?

我想将以下字符串转换为数组/嵌套数组:
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,[array]]"

码:

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...