有没有办法在Ruby中将逗号分隔的字符串转换为数组?例如,如果我有这样一个字符串:
"one,two,three,four"
我该如何将它转换成像这样的数组?
["one", "two", "three", "four"]
有没有办法在Ruby中将逗号分隔的字符串转换为数组?例如,如果我有这样一个字符串:
"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文件)解析为单独的数组:
require "csv"
CSV.parse("one,two\nthree,four")
# [["one","two"],["three","four"]]
str_getcsv
相当的函数,可以自动处理带引号的CSV、包含(转义)逗号的值、多行CSV等? - Lèse majesté"one, two, three, four".split(/\s*,\s*/)
. 这里使用了正则表达式进行字符串分割。如果你更喜欢另一种语法,也可以使用 map
方法实现:"one, two, three, four".split(',').map(&:strip)
。无论哪种方法,最终的目的都是将字符串按逗号分隔并去除空格。 - Kevin Sylvestrerequire 'csv'
CSV.parse_line('one,two,three,four') #=> ["one", "two", "three", "four"]
nil
,例如CSV.parse_line("one,two,,four") #=> ["one", "two", nil, "four"]
。 - Mark Swardstrom>> "one,two,three,four".split ","
=> ["one", "two", "three", "four"]
' one , two,three, four '.split(',').map { | item | item.strip }
#=> ['one', 'two', 'three', 'four']