Last active
February 27, 2020 07:18
-
-
Save Wintus/b67fc085f062b664962e9c12d31dc32f to your computer and use it in GitHub Desktop.
Ruby meta-programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Extended | |
refine Object do | |
alias_method :eigenclass, :singleton_class | |
# http://melborne.github.io/2012/07/12/object-repeat-take-care-of-sequence/ | |
def repeat(init = true) # assume &block is given | |
x = self | |
Enumerator.new do |y| | |
y << x if init | |
loop { y << (x = yield x) } | |
end | |
end | |
end | |
refine Class do | |
alias_method :metaclass, :singleton_class | |
end | |
end | |
using Extended | |
require 'pp' | |
# pp Class.singleton_class | |
pp Class.metaclass | |
puts | |
# pp Class.repeat(&:singleton_class).take(7) | |
pp *Class.repeat { |klass| klass.metaclass }.take(7) | |
puts | |
pp Class.repeat(&:itself).take(3) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# cyclic chain | |
module Rec | |
include self | |
rescue StandardError => e | |
p e | |
end |
https://bugs.ruby-lang.org/issues/6758
# generate enum by func
class Enumerator
class << self
def produce(obj, &block)
new do |y|
y << obj
loop { y << (obj = yield obj) }
end
end
end
end
init
オプションは drop
で十分
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ruby's meta* class
stdout