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

时间:2022-04-08 00:17:43

Is there any way to convert a comma separated string into an array in Ruby? For instance, if I had a string like this:

在Ruby中是否有办法将逗号分隔的字符串转换成数组?例如,如果我有这样一个字符串:

"one,two,three,four"

How would I convert it into an array like this?

如何将它转换成这样的数组?

["one", "two", "three", "four"]

3 个解决方案

#1


114  

Use the split method to do it:

使用分割方法:

"one,two,three,four".split(',')
# ["one","two","three","four"]

If you want to ignore leading / trailing whitespace use:

如果您想忽略前导/后导空白,请使用:

"one , two , three , four".split(/\s*,\s*/)
# ["one", "two", "three", "four"]

If you want to parse multiple lines (i.e. a CSV file) into separate arrays:

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

require "csv"
CSV.parse("one,two\nthree,four")
# [["one","two"],["three","four"]]

#2


15  

require 'csv'
CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"]

#3


9  

>> "one,two,three,four".split ","
=> ["one", "two", "three", "four"]

#1


114  

Use the split method to do it:

使用分割方法:

"one,two,three,four".split(',')
# ["one","two","three","four"]

If you want to ignore leading / trailing whitespace use:

如果您想忽略前导/后导空白,请使用:

"one , two , three , four".split(/\s*,\s*/)
# ["one", "two", "three", "four"]

If you want to parse multiple lines (i.e. a CSV file) into separate arrays:

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

require "csv"
CSV.parse("one,two\nthree,four")
# [["one","two"],["three","four"]]

#2


15  

require 'csv'
CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"]

#3


9  

>> "one,two,three,four".split ","
=> ["one", "two", "three", "four"]