11

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" ... ]
1
  • You should just give the string. Writing params[:value] is irrelevant to the question and is misleading. Commented Apr 1, 2011 at 17:00

3 Answers 3

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

String#split is what you need

Sign up to request clarification or add additional context in comments.

Comments

14

Try this:

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

Comments

6

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.