Skip to content

Instantly share code, notes, and snippets.

@plexus
Created October 14, 2013 20:26
Show Gist options
  • Save plexus/6981661 to your computer and use it in GitHub Desktop.
Save plexus/6981661 to your computer and use it in GitHub Desktop.
class Enumerator
def extract(&blk)
self.each do |obj|
blk.call(*blk.parameters.map(&:last).map {|attr| obj.send(attr)})
end
end
end
Treasure = Struct.new(:coins, :gems)
treasures = [
Treasure.new(100, %w[emerald ruby]),
Treasure.new(70, %w[amethyst], [])
]
treasures.each.extract do |coins|
coins # => 100, 70
end
treasures.each.extract do |gems|
gems # => ["emerald", "ruby"], ["amethyst"]
end
@petervandenabeele
Copy link

Sure this compiles ?

I had to fix it for ruby 2.0 :

/Users/peter_v/t $ ruby -v
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]

/Users/peter_v/t $ git diff
diff --git a/t.rb b/t.rb
index 6fcf6dd..32c001c 100644
--- a/t.rb
+++ b/t.rb
@@ -10,13 +10,13 @@ Treasure = Struct.new(:coins, :gems)

 treasures = [
   Treasure.new(100, %w[emerald ruby]),
-  Treasure.new(70, %w[amethyst], [])
+  Treasure.new(70, %w[amethyst])
 ]

 treasures.each.extract do |coins|
-  coins # => 100, 70
+  puts coins # => 100, 70
 end

 treasures.each.extract do |gems|
-  gems # => ["emerald", "ruby"], ["amethyst"]
+  puts gems # => ["emerald", "ruby"], ["amethyst"]
 end
/Users/peter_v/t $ ruby t.rb 
100
70
emerald
ruby
amethyst

@plexus
Copy link
Author

plexus commented Oct 14, 2013

you're right, that empty array is a leftover from earlier code.

@petervandenabeele
Copy link

Thanks for the confirmation.

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