Marco
Marco

Reputation: 10823

Remove element from array

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.

Upvotes: 7

Views: 9691

Answers (2)

acadavid
acadavid

Reputation: 506

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

Upvotes: 6

Jordan Running
Jordan Running

Reputation: 106147

my_array = [ 1, 2, 3 ]

item = my_array.pop

puts item
# => 3

puts my_array
# => [ 1, 2 ]

Upvotes: 8

Related Questions