如何将字符串拆分为数组作为整数

给出这样的东西

@grid = "4x3".split("x") 

当前结果是字符串“4”,“3”的数组

有没有将它直接拆分为整数的快捷方式?

 ruby-1.9.2-p136 :001 > left, right = "4x3".split("x").map(&:to_i) => [4, 3] ruby-1.9.2-p136 :002 > left => 4 ruby-1.9.2-p136 :003 > right => 3 

在结果数组上调用映射以转换为整数,并分别向左和向右分配每个值。

 "4x3".split("x").map(&:to_i) 

如果你不想过于严格,

 "4x3".split("x").map {|i| Integer(i) } 

如果你想要抛出exception,如果数字看起来不像整数(比如“koi4xfish”)

 >> "4x3".split("x").map(&:to_i) => [4, 3] 

您是否尝试过查看上一个问题的答案中提到的表达式解析器是否允许您这样做?