Skip to content

Instantly share code, notes, and snippets.

@drbrain
Last active November 9, 2017 00:57
Show Gist options
  • Save drbrain/e55a2585c262b16f68e07cfb3839686d to your computer and use it in GitHub Desktop.
Save drbrain/e55a2585c262b16f68e07cfb3839686d to your computer and use it in GitHub Desktop.
You can't use `enum_for __method__` with inheritance 😢
class A
def m(&block)
#return enum_for __method__ unless block_given?
# The above calls the B implementation of #m so instead we have to create
# our own Enumerator that's bound to this class' method so we can run the
# with-block version of this method
unless block_given? then
enum = Enumerator.new do |yielder|
method = A.instance_method(__method__).bind self
block = proc do |object|
yielder << object
end
method.call(&block)
end
return enum
end
yield 1
yield 1
yield 2
yield 2
yield 3
yield 3
end
end
class B < A
def m(&block)
return enum_for __method__ unless block_given?
super(&nil).uniq.each do |number|
yield number * number
end
end
end
p B.new.m.to_a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment