Reputation: 65
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
Reputation: 1278
In your code block above, @array
is not an array, it's a string.
@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])
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']
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
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
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