Reputation: 7391
PHP allows to add values to array like this:
array[]='a' # result: arr[0]='a'
array[]='a' # result: arr[1]='a'
...
How to achieve similar result with Ruby?
UPDATED: forgot to say, that I need to make some extra hashes inside, like
'a'=>{1=>1}...
UPDATE 2:
First update can be a little bit confusing, so there is my full source, which doesn't work. It has to make multiple records of @value
hash in session[:items][0], session[:items][1]...
@value = {'id'=>id, 'quantity'=>1, "property_categories"=>params[:property_categories]}
if !session[:items].present?
session[:items] = @value
else
session[:items].push(@value)
end
UPDATE 3: data should look like:
[0=>{'id'=>id, 'quantity'=>1, "property_categories"=>{1=>1}},
1=>{'id'=>id, 'quantity'=>1, "property_categories"=>{1=>1}}]...
Upvotes: 0
Views: 92
Reputation: 29124
In your code, if session[:items]
is not present, you are assigning @value
(which is a Hash
) to it. So next time it will try to push items to Hash.
If you need an Array
for session[:items]
, this should work
if !session[:items].present?
session[:items] = [@value] # Here create an array with @value in it
else
session[:items].push(@value)
end
EDIT I see you have updated your question. So here is my updated answer
if !session[:items].present?
session[:items] = { 0 => @value }
else
session[:items][ session[:items].keys.max + 1 ] = @value
end
Upvotes: 2
Reputation: 37409
Simply push to the array using <<
array = []
array << 'a' # array == ["a"]
array << 'a' # array == ["a", "a"]
Upvotes: 2
Reputation: 4218
this should work:
arr << 'a'
or this:
arr.push('a')
source: http://www.ruby-doc.org/core-2.1.1/Array.html
Upvotes: 3