Skip to content

Instantly share code, notes, and snippets.

@Wintus
Last active February 27, 2020 07:18
Show Gist options
  • Save Wintus/b67fc085f062b664962e9c12d31dc32f to your computer and use it in GitHub Desktop.
Save Wintus/b67fc085f062b664962e9c12d31dc32f to your computer and use it in GitHub Desktop.
Ruby meta-programming
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)
# cyclic chain
module Rec
include self
rescue StandardError => e
p e
end
@Wintus
Copy link
Author

Wintus commented Nov 26, 2016

Ruby's meta* class

stdout

#<Class:Class>

Class
#<Class:Class>
#<Class:#<Class:Class>>
#<Class:#<Class:#<Class:Class>>>
#<Class:#<Class:#<Class:#<Class:Class>>>>
#<Class:#<Class:#<Class:#<Class:#<Class:Class>>>>>
#<Class:#<Class:#<Class:#<Class:#<Class:#<Class:Class>>>>>>

[Class, Class, Class]

@Wintus
Copy link
Author

Wintus commented Dec 22, 2016

@Wintus
Copy link
Author

Wintus commented Feb 5, 2019

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