简体   繁体   English

如何在Ruby中将字符串转换为数组

[英]How to convert an String into Array in Ruby

In ruby, I have an array with an string value: 在ruby中,我有一个带有字符串值的数组:

my_array=["210,207,203,199,169,165,159,152,148,144,140,137"]

How do I convert it into an normal array like this: 我如何将其转换为如下所示的普通数组:

my_array=[210,207,203,199,169,165,159,152,148,144,140,137]

Note: all the elements are non-negative values. 注意:所有元素均为非负值。
I know I can do this by trim the double quote manually, but I am wondering if there is an more elegant way to implement this? 我知道我可以通过手动修剪双引号来做到这一点,但我想知道是否有更优雅的方法来实现这一点?

我认为这应该工作:

my_array = my_array[0].split(',').map(&:to_i)

Expanding davidrac's answer, you could also use String#scan instead of String#split : 扩展davidrac的答案,您还可以使用String#scan代替String#split

my_array = my_array[0].scan(/\d+/).map(&:to_i)

EDIT 编辑

The benchmarks on this clear show that String#scan is slower: 这个清晰的基准表明String#scan速度较慢:

require 'benchmark'
string = "210,207,203,199,169,165,159,152,148,144,140,137"
Benchmark.bm do |x|
  x.report('split') { 1_000_000.times { string.split(',').map(&:to_i) } }
  x.report('scan') { 1_000_000.times { string.scan(/\d+/).map(&:to_i) } }
end

yields: 产量:

           user     system      total        real
split  3.550000   0.010000   3.560000 (  3.580334)
scan   7.350000   0.020000   7.370000 (  7.402508)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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