从字符串转换为整数时,collect 删除 0

Collect removes 0 when converting from string to integer

当我使用 collect(&:to_i) 将字符串数组更改为整数数组时,如果索引位置 0 处的字符串为“0”,则在转换数组时将其删除。例如:

n = "0123456789"
number = n.split
array = number.collect(&:to_i)
=> [123456789]

去掉前导 0。

但是如果我这样做:

n = "1230456789"
number = n.split
array = number.collect(&:to_i)
=> [1230456789]

并保留 0。

为什么 collect 删除位于位置 0 的 0,但当它位于数组中的其他位置时却不理会它?

查看第一个示例中的数字。它是一个单元素数组。如此有效,这会产生一个只有一个元素的数组:"0123456789".to_i

试试这个:

n = "0 1 2 3 4 5 6 7 8 9"
numbers = n.split
array = numbers.collect(&:to_i)