Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from array

Tags:

ruby

I have an array in my Rails 3.1 apps that has made by several objects:

[#<Hardware id: 10, brand_id: 5, model: "B4200", description: "Stampante OKI B4200", typology_id: 3, sub_typology_id: 10, created_at: nil, updated_at: nil>, #<Hardware id: 19, brand_id: 9, model: "JetLab", description: "JetLab - 600 ", typology_id: 5, sub_typology_id: nil, created_at: nil, updated_at: nil>]

and I want remove one object from this array. Using Rails console, I've tried to do something such as (try to remove first object):

array.pop=#<Hardware id: 10, brand_id: 5, model: "B4200", description: "Stampante OKI B4200", typology_id: 3, sub_typology_id: 10, created_at: nil, updated_at: nil>

but it doesn't work. How can I do this?

UPDATED: My goal isn't to pop last element on array, but a generic object (everywhere inside array) that I should find using mysql search query.

like image 715
Marco Avatar asked Apr 20 '12 17:04

Marco


2 Answers

my_array = [ 1, 2, 3 ]

item = my_array.pop

puts item
# => 3

puts my_array
# => [ 1, 2 ]
like image 142
Jordan Running Avatar answered Sep 30 '22 07:09

Jordan Running


You probably want to use the Array#delete function

an_array = [1,3,4]
an_array.delete(3)
# => 3
puts an_array
# => [1,4]

Check it out in the Ruby documentation:

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-delete

like image 36
acadavid Avatar answered Sep 30 '22 06:09

acadavid