如何将逗号分隔的字符串转换为数组?

Mar*_*ski 68 ruby csv arrays string

有没有办法将逗号分隔的字符串转换为Ruby中的数组?例如,如果我有这样的字符串:

"one,two,three,four"
Run Code Online (Sandbox Code Playgroud)

我怎么把它转换成这样的数组?

["one", "two", "three", "four"]
Run Code Online (Sandbox Code Playgroud)

Kev*_*tre 132

使用该split方法执行此操作:

"one,two,three,four".split(',')
# ["one","two","three","four"]
Run Code Online (Sandbox Code Playgroud)

如果要忽略前导/尾随空格,请使用:

"one , two , three , four".split(/\s*,\s*/)
# ["one", "two", "three", "four"]
Run Code Online (Sandbox Code Playgroud)

如果要将多行(即CSV文件)解析为单独的数组:

require "csv"
CSV.parse("one,two\nthree,four")
# [["one","two"],["three","four"]]
Run Code Online (Sandbox Code Playgroud)

  • @vanboom`"一,二,三,四".split(/\s*,\ s*/)`.Split也可以使用正则表达式.或者你可以使用`map`方法,如果你更喜欢这种语法:`"一,二,三,四".split(',').map(&:strip)` (5认同)

eph*_*ent 16

require 'csv'
CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"]
Run Code Online (Sandbox Code Playgroud)


Dig*_*oss 9

>> "one,two,three,four".split ","
=> ["one", "two", "three", "four"]
Run Code Online (Sandbox Code Playgroud)