有没有办法将逗号分隔的字符串转换为Ruby中的数组?例如,如果我有这样的字符串:
"one,two,three,four"
我如何将其转换为这样的数组?
["one", "two", "three", "four"]
答案 0 :(得分:127)
使用split
方法执行此操作:
"one,two,three,four".split(',')
# ["one","two","three","four"]
如果要忽略前导/尾随空格,请使用:
"one , two , three , four".split(/\s*,\s*/)
# ["one", "two", "three", "four"]
如果要将多行(即CSV文件)解析为单独的数组:
require "csv"
CSV.parse("one,two\nthree,four")
# [["one","two"],["three","four"]]
答案 1 :(得分:15)
require 'csv'
CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"]
答案 2 :(得分:9)
>> "one,two,three,four".split ","
=> ["one", "two", "three", "four"]