如何将逗号分隔的字符串转换为数组? [英] How do I convert a comma-separated string into an array?

查看:456
本文介绍了如何将逗号分隔的字符串转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将逗号分隔的字符串转换成Ruby中的数组?例如,如果我有这样的字符串:

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

推荐答案

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

这篇关于如何将逗号分隔的字符串转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆