Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string into array as integers

Tags:

ruby

Given something like this

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

The current result is an array of strings "4","3"

Is there any shortcut to split it directly to integers?

like image 812
Martin Avatar asked Apr 07 '11 01:04

Martin


2 Answers

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.

like image 98
Mike Lewis Avatar answered Oct 17 '22 00:10

Mike Lewis


"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")

like image 44
EdvardM Avatar answered Oct 17 '22 01:10

EdvardM