如何将逗号分隔的string转换为数组?
有什么办法在Ruby中将逗号分隔的string转换为数组? 例如,如果我有这样一个string:
"one,two,three,four"
我将如何将它转换成这样的数组?
["one", "two", "three", "four"]
使用split
方法来做到这一点:
"one,two,three,four".split(',') # ["one","two","three","four"]
如果你想忽略前导/尾随空白的使用:
"one , two , three , four".split(/\s*,\s*/) # ["one", "two", "three", "four"]
如果你想把多行(即一个CSV文件)parsing成单独的数组:
require "csv" CSV.parse("one,two\nthree,four") # [["one","two"],["three","four"]]
require 'csv' CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"]
>> "one,two,three,four".split "," => ["one", "two", "three", "four"]