ç¶æ¿, mix-in, include, extend ã«ã¤ãã¦è¦ãæ¸ã
ç¶æ¿
- rubyã§ã¯åä¸ç¶æ¿ã®ã¿
- å¤éç¶æ¿ã¯ãmix-in(å¾è¿°)ã¨ããæ¦å¿µã§å¯¾å¿ãã¦ãã
class SuperClass def super_say p "super_hello" end end class SubClass < SuperClass def sub_say p "sub_hello" end def super_say p "sub_super_hello" # 親ã¯ã©ã¹ã®ã¡ã½ããå¼ã³åºã super end end subClass = SubClass.new subClass.sub_say # sub_hello subClass.super_say # sub_super_hello, super_hello
ã¢ã¸ã¥ã¼ã«
- æ¦å¿µçã«ã¯ãã¯ã©ã¹ã«è¿ãããã¤ã³ã¹ã¿ã³ã¹ããµãã¯ã©ã¹ã¯ä½ããªã(å¾è¿°ããmix-inã®çº)
- å®ã¯ãClass 㯠Module ã® ãµãã¯ã©ã¹
- åå空éã«ä½¿ããã®ã¨ããã¤ã¡ã¼ã¸ã ãã©ãmix-in ã¨ããæ¦å¿µã«ã使ãã
module TestModule # ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ãã # ã¢ã¸ã¥ã¼ã«ã¯ãã¤ã³ã¹ã¿ã³ã¹ãä½ããªãã®ã§ãå¼ã³åºããªã def say p "hello" end # ã¢ã¸ã¥ã¼ã«ã®ç¹ç°ã¡ã½ãã def self.say p "hello_self" end end # ç¹ç°ã¡ã½ãããå¼ã³åºããã TestModule.say # hello_self
mix-in
以ä¸ã®ç¹å¾´ãæã¤æ½è±¡ã¯ã©ã¹(mix-in ã¯ã©ã¹)ã®ã¿å¤éç¶æ¿ã許å¯ããäºã§ãå¤éç¶æ¿ãå®å
¨ã«è¡ãä»çµã¿
- åç¬ã§ã¤ã³ã¹ã¿ã³ã¹ãä½ããªã
- é常ã®ã¯ã©ã¹ããç¶æ¿ããªã
include
- Module#include
- ã¯ã©ã¹ã«å¯¾è±¡ã®ã¢ã¸ã¥ã¼ã«ã mix-in ããã
# ã¯ã©ã¹ã«include class IncludedClass include TestModule end includedClass = IncludedClass.new IncludedClass.say # hello
ã¢ã¸ã¥ã¼ã«é¢æ°
- ã¢ã¸ã¥ã¼ã«ã®ã¡ã½ããã¨ãã¦ããã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã¨ãã¦ã使ããé¢æ°
- Ruby用語集 - Rubyリファレンスマニュアル # モジュール関数
module TestModule def say p "hello" end # ã¢ã¸ã¥ã¼ã«é¢æ°ãå®ç¾© module_function :module_func_say end # ã¢ã¸ã¥ã¼ã«ã®ç¹ç°ã¡ã½ããã¨ãã¦ãå¼ã¹ã TestModule.say # hello class TestClass def saysay say end end # ã¤ã³ã¹ã¿ã³ã¹ãããå¼ã¹ã TestClass.new.saysay
extend
- Object#extend
- ãªãã¸ã§ã¯ãã®ç¹ç°ã¡ã½ããã¨ãã¦ã対象ã®ãªãã¸ã§ã¯ãã®ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã追å
- ãªãã¸ã§ã¯ãã®ç¹ç°ã¡ã½ããã¯ã追å ãããªã
# ã¯ã©ã¹ã«extend class ExtendedClass extend TestModule end ExtendedClass.say # hello extendedClass = ExtendedClass.new # ã¯ã©ã¹ã®ç¹ç°ã¡ã½ãã(ã¯ã©ã¹ã¡ã½ãã)ã¨ãã¦è¿½å ãããã®ã§ã # ã¤ã³ã¹ã¿ã³ã¹ã«ã¯å½±é¿ããªã #extendedClass.say # NoMethodError # ã¤ã³ã¹ã¿ã³ã¹ã«extend extendedClass.extend TestModule extendedClass.say # hello
mainã«extend
- mainã«extendããã°ãã©ãããã§ãå¼ã³åºãã
# mainã®ç¹ç°ã¡ã½ããã¨ãã¦è¿½å ããã extend TestModule say # hello