且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-14 12:57:48

使用split方法执行此操作:

"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"]

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

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

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