Last active
December 16, 2015 21:49
-
-
Save tenten0213/5502036 to your computer and use it in GitHub Desktop.
おまじないについて その2
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
class Foo | |
# attr_*はModuleのprivate methodなので、レシーバは省略する | |
# ClassはModuleを継承していて、FooはClassを継承している | |
# ので、Moduleのprivate methodのattr_accessorがFooの中で利用可能 | |
attr_accessor :value | |
end | |
foo = Foo.new | |
foo.value = 'z' | |
puts foo.value #=> z | |
# ancestorsはクラスの継承チェーンを辿る | |
puts Class.ancestors #=> Class, Module, Object, Kernel, BasicObject | |
puts Module.method(:attr_accessor) #=> #<Method: Class(Module)#attr_accessor> | |
puts Module.private_methods # inherited, ... attr, attr_reader, attr_writer, attr_accessor, remove_const, ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Classはクラスのクラスです。
puts Class.ancestors を見てみると、ClassクラスはModuleクラスを継承していることがわかると思います。
puts Module.private_methodsを見てみると、attr_*があることが確認できます。
Rubyのprivateメソッドはレシーバを省略した形で記述します。(self.attr_accessorとは書けない)
attr__はModuleのprivateメソッドで、ClassはModuleを継承しています。ということは、selfがClassであってもModuleであってもattr__を利用することが可能です。
これをクラスマクロと言います。