如何在Ruby中分割定界字符串并将其转换为数组? [英] How to split a delimited string in Ruby and convert it to an array?
本文介绍了如何在Ruby中分割定界字符串并将其转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
"1,2,3,4"
,我想将其转换为数组:
and I'd like to convert it into an array:
[1,2,3,4]
如何?
推荐答案
>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]
或整数:
>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]
或者对于更高版本的ruby(> = 1.9-如Alex指出的那样):
Or for later versions of ruby (>= 1.9 - as pointed out by Alex):
>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]
这篇关于如何在Ruby中分割定界字符串并将其转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文