Split a string into an array of numbers

28,974

Solution 1

result = params[:value].split(/,/)

String#split is what you need

Solution 2

Try this:

arr = "07016,07023,07027".split(",")

Solution 3

Note that what you ask for is not an array of separate numbers, but an array of strings that look like numbers. As noted by others, you can get that with:

arr = params[:value].split(',')

# Alternatively, assuming integers only
arr = params[:value].scan(/\d+/)

If you actually wanted an array of numbers (Integers), you could do it like so:

arr = params[:value].split(',').map{ |s| s.to_i }

# Or, for Ruby 1.8.7+
arr = params[:value].split(',').map(&:to_i)

# Silly alternative
arr = []; params[:value].scan(/\d+/){ |s| arr << s.to_i }
Share:
28,974

Related videos on Youtube

Trip
Author by

Trip

I program Ruby, C#, iOS, Node, and Augmented Reality for Unity3D. I write PostgreSQL, mySQL, SQLite, and MongoDB. I use Heroku, Amazon, Microsoft Azure. Creator of the Yoga Sutras App, Braidio Mobile, and Braidio. In my spare time, I teach Ashtanga Yoga. elephant trip AT gmail DOT com #happyToHelp

Updated on July 09, 2022

Comments

  • Trip
    Trip almost 2 years

    My string:

    >> pp params[:value]
    "07016,07023,07027,07033,07036,07060,07062,07063,07065,07066,07076,07081,07083,07088,07090,07092,07201,07202,07203,07204,07205,07206,07208,07901,07922,07974,08812,07061,07091,07207,07902"
    

    How can this become an array of separate numbers like :

    ["07016", "07023", "07033" ... ]
    

Related