简体   繁体   中英

How do I convert a comma-separated string into an array?

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

"one,two,three,four"

How would I convert it into an array like this?

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

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 (ie a CSV file) into separate arrays:

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

If your string has an unknown number of whitespaces before/after in any order/number, then you can also do the following:

'  one  ,   two,three, four   '.split(',').map { | item | item.strip }

#=> ['one', 'two', 'three', 'four']

Wrote a blog post for those who're interested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM