Skip to content

Instantly share code, notes, and snippets.

@tenten0213
Last active December 16, 2015 21:49
Show Gist options
  • Save tenten0213/5502036 to your computer and use it in GitHub Desktop.
Save tenten0213/5502036 to your computer and use it in GitHub Desktop.
おまじないについて その2
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, ...
@tenten0213
Copy link
Author

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__を利用することが可能です。

これをクラスマクロと言います。

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