1

I am adding to an array using:

server.bans << { :mask => "#{user}", :who => "#{server}", :when => Time.now.to_i }

What is the simplest method to reverse this command?

Should I be using .remove? If so what should I pass to it, the same as what I used in the <<?

4 Answers 4

2

You can use Array#pop to remove the last element of the array:

server.bans.pop
Sign up to request clarification or add additional context in comments.

Comments

2

You can also use Array#delete_if, if you want to remove elements which meet certain criteria:

server.bans.delete_if{ |u| u[:mask] == "#{user}" }

2 Comments

I think reject! is the more commonly used one, but both work the same way.
Hmm, this doesn't work for me and I'm wondering why. The ban still exists in server.bans :-/
1

You could get the object_id of each element in the Array to use as a future reference. While using pop will work, it is not available once another element of the Array is added.

To view object_id of elements. Possibly store these in it's own Array.

server.bans do |ban|
  puts ban.object_id
end

Comments

-1

Ruby array provide delete_if method to delete items from array conditions. You can use this method as

server.bans.delete_if{ |u| u[:mask] == user.to_s }

To get more details of delete_if http://ruby-doc.org/core-2.2.2/Array.html#method-i-delete_if

Further you can also user remove! method

1 Comment

Is this not the same as @Karsten's earlier answer (except for to_s, which is incorrect)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.