ã¡ã¿ããã°ã©ãã³ã°Rubyèªæ¸ä¼ 第2å
ï¼æï¼æ¥ã«ã¡ã¿ããã°ã©ãã³ã°Rubyèªæ¸ä¼ãå®æ½ãã¾ããã
ã¡ã¿ããã°ã©ãã³ã°Ruby ã®ä¸ã§ãã«ã¬ã³ãã¯ã©ã¹ã¨ããç¨èªã説æããã¦ãã¾ãããã
説æãåããã«ããããã«æããã®ã§æ°ãã«æ´çãã¦ãããã¨æãã¾ãã
ã«ã¬ã³ãã¯ã©ã¹ã¨ã¯ãdef method_name args ... end ã®ãããªæ¸ãæ¹ã§ãã¡ã½ãããå®ç¾©ãããå ´æã®ãã¨ã§ãã
ã«ã¬ã³ãã¯ã©ã¹ã¯æ¬¡ã®ããã«èãããã¨ãã§ãã¾ãã
- ã¯ã©ã¹ã®ã³ã³ããã¹ãã§ããã°ãç¾å¨ã®ã¯ã©ã¹
- ãªãã¸ã§ã¯ãã®ã³ã³ããã¹ãã§ããã°ãself ã®ãªãã¸ã§ã¯ãã®ç¹ç°ã¯ã©ã¹
ã¯ã©ã¹ã®ã³ã³ããã¹ãã«é·ç§»ããæ¹æ³ã¯æ¬¡ã®ï¼éãããããã®å ´åã¯ãã®ã¯ã©ã¹ãã«ã¬ã³ãã¯ã©ã¹ã«ãªãã¾ãã
- class ã¾ã㯠module ãã¼ã¯ã¼ãã§ã¯ã©ã¹ï¼ã¢ã¸ã¥ã¼ã«ï¼ããªã¼ãã³ãã
- class_eval ã§ã¬ã·ã¼ãã®ã¯ã©ã¹ããªã¼ãã³ãã
éã«ãªãã¸ã§ã¯ãã®ã³ã³ããã¹ãã«é·ç§»ããã«ã¯ãinstance_eval ã使ããã¨ã«ãªãã¾ãããã®å ´åã¯ãã®ãªãã¸ã§ã¯ãã®ç¹ç°ã¯ã©ã¹ãã«ã¬ã³ãã¯ã©ã¹ã«ãªãã¾ã
ã¤ã¾ãã instance_eval ã®ä¸ã® def ã¯ãã®ãªãã¸ã§ã¯ãã®ç¹ç°ã¡ã½ããå®ç¾©ã«ãªãã¾ã
ã¯ã©ã¹ã®ã³ã³ããã¹ãã¸ã®é·ç§»ã®ä¸ã§ç¹ã«ãclass <
# (1) ãããã¬ãã«ã®ã¡ã½ããå®ç¾©ï¼ Object ã«å®ç¾©ãããï¼ def toplevel_method end # (2) ã¯ã©ã¹ã®ã³ã³ããã¹ãã§ã®ã¡ã½ããå®ç¾© # ã¯ã©ã¹A ã®ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã¨ãã¦å®ç¾©ããã class A def instance_method1 end end # (3) class_eval ãå©ç¨ãã¦ã¯ã©ã¹ã®ã³ã³ããã¹ãã§ã¡ã½ããå®ç¾© # ã¯ã©ã¹A ã®ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã¨ãã¦å®ç¾©ããã A.class_eval do def instance_method2 end end # (4) ç¹ç°ã¯ã©ã¹ã®ã³ã³ããã¹ãã§å®è¡ããããã®è¨æ³ <