Ruby on Rails: remove an element from an array by id

Is there any short arm for

  @notifications = Notification.find(:all, :conditions => ['expires_at > ?', Time.now])

  notif = Notification.find(:all, cookie[0].to_i)
  @notifications.delete(notif[0]) if not notif.empty?

cookie is the identifier of the notification stored in cookies. it is in an iteration that removes notifications that the user does not want to see.

thank! =)

+3
source share
2 answers

If it is an array of activerecord objects, you can remove them from the database as follows.

Notification.delete_all(:id => cookie[0].to_i)

If it's just an array, you can use delete if

@notifications.delete_if{|x| x == cookie[0].to_i}

+7
source

Now you can simply use the method delete_at( index ):

array = ['item0', 'item1', 2, 3]
array.delete_at 1
# => "item1" 
array.delete_at 2
# => 3
array
# => ["item0", 3] 

You can do the same with slice!( index ).

: delete_at , !, , .

: http://ruby-doc.org/core-2.2.0/Array.html#method-i-delete_at

0

Source: https://habr.com/ru/post/1752537/


All Articles