How to split string into array as integers

21,718

Solution 1

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.

Solution 2

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

Solution 3

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

Related videos on Youtube

Martin
Author by

Martin

Cloud-based ideas starter. I believe that the evolving future of web-apps goes towards the mixing of great engineering (mostly Agile Craftsmanship) and a refined taste for Visual Arts. Its in the right mashup of those two that elegancy, competitiveness and higher-end product is delivered. Skills: Branding and Identity, Managing, Visual Design, Cloud-based architectures, Agile craftsmanship, Investor https://www.yorokobi.com http://martincaetano.com http://twitter.com/PelCasandra

Updated on July 09, 2022

Comments

  • Martin
    Martin almost 2 years

    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?

Related