Skip to content

Instantly share code, notes, and snippets.

@mjtko
Created May 4, 2012 20:29
Show Gist options
  • Save mjtko/2597530 to your computer and use it in GitHub Desktop.
Save mjtko/2597530 to your computer and use it in GitHub Desktop.
Subset for a set
require 'set'
class Set
def subset(&pred)
Set.new.tap do |subset|
each do |x|
subset << x if pred.call(x)
end
end
end
end
@mjtko
Copy link
Author

mjtko commented May 4, 2012

eg.

irb(main):003:0> set = Set[*1..50]
=> #<Set: {49, 38, 27, 16, 5, 44, 33, 22, 11, 50, 39, 28, 17, 6, 45, 34, 23, 12, 1, 40, 29, 18, 7, 46, 35, 24, 13, 2, 41, 30, 19, 8, 47, 36, 25, 14, 3, 42, 31, 20, 9, 48, 37, 26, 15, 4, 43, 32, 21, 10}>
irb(main):004:0> set.subset { |x| x % 7 == 0 }
=> #<Set: {49, 28, 7, 35, 14, 42, 21}>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment