Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pop an element from a Set in Ruby?

Tags:

ruby

set

In Python I can do a_set.pop() and I remove an element from the set and catch it in a variable. Is there a way to do the same thing with a set in Ruby?

like image 292
Adrián Juárez Avatar asked Oct 10 '15 04:10

Adrián Juárez


1 Answers

Ruby Set haven't pop method, but you can do like this:

class Set
  def pop
    temp = self.to_a.pop
    self.delete(temp)
    temp
  end
end

s1 = Set.new [1, 2]
=> #<Set: {1, 2}>
s1.pop
=> 2
s1
=> #<Set: {1}>
like image 108
pangpang Avatar answered Sep 29 '22 09:09

pangpang