开发者

Ruby on Rails: remove element from array by id

Is there some sort of short hand for

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

  noti开发者_如何学运维f = Notification.find(:all, cookie[0].to_i)
  @notifications.delete(notif[0]) if not notif.empty?

cookie is an id of a notification stored into cookies. this is in an iteration, that removes notifications that the user doesn't want to see.

thanks! =)


If this is an array of activerecord objects, you could delete from the database like this.

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

If this is just an array, then you can use the delete if

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


Now you could just use the delete_at( index ) method:

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

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

Note: delete_at is a mutator method even if it doesn't end in !, so don't rely on its return value, it will only be the deleted item.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜