Home > Software design >  Turn one string of multiple numbers separated by commas into array of integers in ruby
Turn one string of multiple numbers separated by commas into array of integers in ruby

Time:07-21

How to turn "1,2,3,4,500,645" into [1,2,3,4,500,645] in Ruby. .to_i only returns the first number

CodePudding user response:

if commas just divide integers

"1,2,3,4,500,645".split(',').map(&:to_i)
=> [1, 2, 3, 4, 500, 645]

if you are not sure what's in the string and you want everything breaks if something not expected is there

"1,2,3,4,500,645".split(',').map { |i| Integer(i) }
=> [1, 2, 3, 4, 500, 645]
  •  Tags:  
  • ruby
  • Related