Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take and remove elements from a Ruby Set in one operation

Tags:

ruby

set

I have a Set of elements from which I want to take and remove the first few elements a bunch of times. Is there a shorter way (so one operation instead of two) to do that than this:

require 'set'
s = Set[1, 2, 3, 4]       # => #<Set: {1, 2, 3, 4}> 

first_two = s.take(2)     # => [1, 2]
s.subtract(first_two)     # => #<Set: {3, 4}>

(So basically I'm wondering whether I'm overlooking a shift for Sets)

like image 858
Confusion Avatar asked Jan 30 '13 14:01

Confusion


Video Answer


3 Answers

You could add a new method take! (or remove! or whatever name seems appropriate) to the Set class:

class Set
  def take!(args)
    taken = self.take(args)
    self.subtract(taken)
    return taken
  end
end

a = Set[1, 2, 3, 4] # <Set: {1, 2, 3, 4}>
a.take!(2) # <Set: {1, 2}>
a # <Set: {3, 4}>
like image 183
Conkerchen Avatar answered Oct 18 '22 21:10

Conkerchen


There is no shorter way using builtin methods.

There is an open feature request for a method to return and remove one element; you may want to help refine the API?

like image 45
Marc-André Lafortune Avatar answered Oct 18 '22 19:10

Marc-André Lafortune


From http://www.ruby-doc.org/stdlib-1.9.3/libdoc/set/rdoc/Set.html:

Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup.

It would be odd and probably illogical to implement methods like shift and pop on an object that knows nothing about index.

like image 1
ichigolas Avatar answered Oct 18 '22 19:10

ichigolas