b.herring
b.herring

Reputation: 643

Turn one string of multiple numbers separated by commas into array of integers in ruby

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

Upvotes: 0

Views: 63

Answers (1)

Ursus
Ursus

Reputation: 30056

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]

Upvotes: 2

Related Questions