Boris
Boris

Reputation: 65

How do I add element to a comma-delimited string?

I have an array (in test_controller.rb):

@array = "123,456,789,012,345"

Also, I have a variable:

@var = params[:q] #I get it from the web form.

Tell me please, how can I add this variable to an array?

Upvotes: 2

Views: 2393

Answers (3)

Shannon Scott Schupbach
Shannon Scott Schupbach

Reputation: 1278

In your code block above, @array is not an array, it's a string.

Change the way you set the value of @array

If you're setting the value of @array somewhere else, to make it an array of integers, replace the double quotes with square brackets:

@array = [123, 456, 789, 012, 345]

Then you can push or shovel the new value in:

@array << params[:q]
or
@array.push(params[:q])

Convert String to Array

Alternately if you want the numbers to remain strings for some reason, just convert the string into an array using the String#split method:

@array = "123,456,789,012,345".split(',') #=> ['123', '456', '789', '012', '345']

Just append to String

You could also just add the new value (as a string) to the existing string:

@array += ",#{params[:q]}"

So if params[:q] were set to 678, this would turn the integer into a string and add it to the existing string with a leading-comma.

But then you should probably rename @array to @string to be more precise.

Upvotes: 1

Aravind.S
Aravind.S

Reputation: 186

 # The following lines add the element as the last element in the array
array[array.length] = element
array += [element]
array << element
array.push(element)
array.append(element)

# To add it at a specific position, use insert 
array.insert(position, element)

As people have already mentioned, @array in your case is a String and not an Array.

Upvotes: 0

Sam
Sam

Reputation: 33

Your array will have to be in brackets. Right now your instance variable of array (@array) is actually a String. You'll want to put your string into an array like so:

array = [123,456,789,012,345]

There are different ways to put your variable into your array. You can certainly shovel it in:

 array << params[:q]

If you want the values in your array to remain in a string, you can use the split method:

@array.split or @array.split(',')

Pull up IRB and plug those in and see if that is what you're looking for. You can also prepend (add to the front) or append (add the end) of your string.

This ruby doc will serve you well: Ruby Doc-Arrays

Good luck!

Upvotes: 0

Related Questions