ãé¢æ°åRubyãã¨ããç (1) - Symbol#to_proc, Object#method
ãã®è¨äºã¯ãRubyãæ¸ãã«ããã£ã¦ãããã«ãããã¯ãæ¸ããã«ãã¾ããããã追æ±ããã誰å¾ãªé£è¼ã§ããã
ã ã£ã¦ããããã¯ã£ã¦æ±ããããï¼ä»®å¼æ°ã®|x|ã¨ããã¢ã¤ã
Symbol#to_proc
åºæ¬ä¸ã®åºæ¬ã
instance method Symbol#to_proc
以ä¸ã®ãããªArrayããã£ã¦ã
irb(main):003:0> arr = [:user, :entry, :article, :comment, :category] => [:user, :entry, :article, :comment, :category]
åè¦ç´ ãto_sãããã£ããã
irb(main):004:0> arr.map{|s| s.to_s} => ["user", "entry", "article", "comment", "category"]
ã¨æ¸ããããã«ã
irb(main):005:0> arr.map(&:to_s) => ["user", "entry", "article", "comment", "category"]
ã£ã¦æ¸ãã°ããã
ããã¯ããããã¯ãåãåãã¡ã½ããã«Proc以å¤ã渡ãããã¨ãto_procãå¼ã³åºãã¦åå¤æãè¡ãä»çµã¿ã«ããã
to_proc ã¡ã½ãããæã¤ãªãã¸ã§ã¯ããªãã°ã`&' 修飾ããå¼æ°ã¨ãã¦æ¸¡ããã¨ãã§ãã¾ããããã©ã«ã㧠ProcãMethod ãªãã¸ã§ ã¯ãã¯å ±ã« to_proc ã¡ã½ãããæã¡ã¾ããto_proc ã¯ã¡ã½ããå¼ã³åºãæã«å® è¡ãããProc ãªãã¸ã§ã¯ããè¿ããã¨ãæå¾ ããã¾ãã
メソッド呼び出し(super・ブロック付き・yield)
Symbol#to_procã®å®è£
ã¯ããããªã¤ã¡ã¼ã¸ãããã¯ãå¼æ°ã«å¯¾ãã¦sendã§Symbolãéãprocãçæãã
def to_proc proc{|obj, *args| obj.send(self, *arg)} end
ãã®ããã«ãªãã
irb(main):006:0> :to_s.to_proc => #<Proc:0x007fcf721c21d8> irb(main):007:0> :to_s.to_proc.call(:user) => "user"
Object#method
Object#methodã¯å¤§å¤ç´ æ´ããããã¹ãããç¡ããã¦é¢æ°åRubyã¯èªããªãã
Object#methodã¯ãã¬ã·ã¼ãã¼ã¨ãªã£ãObjectãããMethodãªãã¸ã§ã¯ããåãåºãã
ãã®Methodãªãã¸ã§ã¯ããããã¡ã½ããåãã¬ã·ã¼ãã¼ã«å¯¾ãã¦å¼ã³åºãProcãä½ãåºããã¨ãã§ããã
irb(main):010:0> method = arr.method(:size) => #<Method: Array#length> irb(main):011:0> method.call => 3 irb(main):012:0> method.to_proc.call => 3
ãã®ä¾ã§ã¯ãarrãªãã¸ã§ã¯ãã«å¯¾ããsizeã¡ã½ããå¼ã³åºãããProcã¨ãã¦åãåºãã¦ããã
Procã¨ãã¦åãåºããã¨ãããã¨ã¯ãç¹å®ã®ãªãã¸ã§ã¯ãã¸ã®ã¡ã½ããå¼ã³åºããProcã¨ããå½¢ã§å¯æ¬æ§ãå¾ã¦ããã¨ãããã
ã¤ã¾ããä¸åº¦Procã«ãã¦ãã¾ãã°ãå¤æ°ã«ä»£å
¥ããããä»ã®é¢æ°ã«å¼æ°ã¨ãã¦æ¸¡ããããããããæ¾é¡çµ¶é ã£ã¦ã¯ã±ãããï¼ãã¡ã¼ã¹ãã¯ã©ã¹ï¼ï¼
ãã®ã¢ããã¼ãã§ãselect, map, injectãªã©ã®ãããã¯ãåãé«éé¢æ°ç¾¤ãããããã¯ãæ¸ããã¨ç¡ãå©ç¨ã§ããã
å
·ä½ä¾ã示ããã
class Criteria def initialize(length) @length = length end def allow?(s) s.length >= @length end end
ãã®Criteriaã¯ã©ã¹ã¯ãallowã¡ã½ããã§ã@lengthã§ãã£ã¦ããå¤ã¨å¼æ°ã®å¤ãæ¯è¼ããã
ä»ãlengthã6ã®Criteriaãªãã¸ã§ã¯ãããããããã«å¯¾ãã¦allow?ãtrueãè¿ããã®ã ãarrã®ä¸ããæ½åºãããã
ãããã¯ã使ãå ´åã¯ããããªãã
irb(main):053:0> criteria = Criteria.new(6) => #<Criteria:0x007fcf71031f90 @length=6> irb(main):054:0> arr.select{|s| criteria.allow? s } => [:article, :comment, :category]
Object#methodãå©ç¨ããã°ãããæ¸ããã
irb(main):055:0> arr.select(&criteria.method(:allow?)) => [:article, :comment, :category]
criteriaãªãã¸ã§ã¯ããããallow?ã¡ã½ããã¸ã®å¼ã³åºããObject#methodã§åãåºãã¦ãselectã«æ¸¡ãã°ããã ãã ã
Symbol#to_procãObject#methodã使ãã°ãåãªãã¡ã½ãããå¼ã³åºããè¡ãããã ãã«ãããããããã¯ãæ¸ããªãã¦ããããªãã
ãã¡ããããã®ã¹ã¿ã¤ã«ãèªã¿ãããã³ã¼ãã§ãããã¯è³å¦ä¸¡è«ããã ãããããã¡ã¼ã¹ã¯ã©ã¹ãªé¢æ°ã®å¯æ¬æ§ãæèãããã¨ã§DRYãªã³ã¼ããå®ç¾ããä¸å©ã¨ã¯ãªãã§ãããã
次åã¯é¢æ°åæã«ã¤ãã¦æ¸ãã( ;ï¾ç¿ï¾)ï¾ï½¼Î£ ï¾ï½¨ï¾ï½·ï¾ï½¨ï½¨ï½°ï½°ï½¯!!!