Given something like this
鉴于这样的
@grid = "4x3".split("x")
The current result is an array of strings "4","3"
当前结果是字符串“4”、“3”的数组
Is there any shortcut to split it directly to integers?
有什么捷径可以把它直接分割成整数吗?
4 个解决方案
#1
36
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
Call map on the resulting array to convert to integers, and assign each value to left and right, respectively.
将结果数组中的调用映射转换为整数,并分别将每个值分配给左和右。
#2
9
"4x3".split("x").map(&:to_i)
if you don't wan to be too strict,
如果你不想太严格,
"4x3".split("x").map {|i| Integer(i) }
if you want to throw exceptions if the numbers don't look like integers (say, "koi4xfish")
如果你想抛出异常,如果数字看起来不像整数(比如,“koi4xfish”)
#3
3
>> "4x3".split("x").map(&:to_i)
=> [4, 3]
#4
0
Have you tried seeing if the expression parser mentioned in an answer to your previous question would allow you to do this?
您是否尝试过查看前面问题的答案中提到的表达式解析器是否允许您这样做?
#1
36
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
Call map on the resulting array to convert to integers, and assign each value to left and right, respectively.
将结果数组中的调用映射转换为整数,并分别将每个值分配给左和右。
#2
9
"4x3".split("x").map(&:to_i)
if you don't wan to be too strict,
如果你不想太严格,
"4x3".split("x").map {|i| Integer(i) }
if you want to throw exceptions if the numbers don't look like integers (say, "koi4xfish")
如果你想抛出异常,如果数字看起来不像整数(比如,“koi4xfish”)
#3
3
>> "4x3".split("x").map(&:to_i)
=> [4, 3]
#4
0
Have you tried seeing if the expression parser mentioned in an answer to your previous question would allow you to do this?
您是否尝试过查看前面问题的答案中提到的表达式解析器是否允许您这样做?