Masa Sakano
2018-10-09 10:21:33 UTC
åéæ£æãšç³ããŸãã
Rubyã®ã¡ãœããããããããã¯ã« $1, $2 (ãå«ãã
Regexp.last_match)
ãæž¡ãæ¹æ³ããªããã®ãããšè³ªåããŸãã
èæ¯ãšããŠã å éšã§ String#sub (gsub)
ãåŒã¶ãããªååã®(duck-typingã®)ã¡ãœãããäœã£ãŠããŸããåçŽåããäŸãæããŸãã
class C
# Stringã®ã€ã³ã¹ã¿ã³ã¹ str ã«å¯ŸããŠãsub() ãå®è¡
def self.sub(str, re, &b)
str.sub(re, &b)
end
end
/(prev)/ =~ 'previous'
p C.sub('baa', /(b)aa/){|a| a+'_'+$1}
# => "baa_prev" (âµ ãããã¯äžã§ ($1 == 'prev'))
# ãã㧠"baa_b" ãåŸãæ¹æ³ãããã?
Rubyã§ã¯ãäžè¬ã«ã$1
ã¯ãããŒã«ã«å€æ°ãšããŠæ±ããããšç解ããŠããŸããRuby
ã®ããŒã«ã«å€æ°ã¯ããããå²ãã¹ã³ãŒãã®å€æ°ãåŒãç¶ããŸããããããã£ãŠãäžã®äŸã§ã¯ãã¡ãœãã
C.sub ã«äžãããããã¯äžã«ãã $1
ã«ã¯ããã®ãããã¯ãå«ãæã®çŽåã®æ£èŠè¡šçŸè©äŸ¡ã®çµæ("prev")ãæž¡ã£ãŠããŸãã
ããããããã§è¡ãããããšã¯ããã¯ã©ã¹ C
ã®(ã¯ã©ã¹)ã¡ãœãã C.sub
ã§è©äŸ¡ãããæ£èŠè¡šçŸã®çµæãã $1
(ãªã©)ãšããŠãããã¯å ã§æ±ãããšã§ãã
çŸå®ã«ãString#sub
ãªã©ã§ã¯ãã¡ãœããå ã§æ£èŠè¡šçŸè©äŸ¡ããçµæã $1
(ãªã©)ãšããŠãããã¯ã«æž¡ãããŠããŠããã®ãããã¯ã®çµæãã¡ãœãã
sub() åŽãã yieldã§ããŠããŸãããããšåãããšã
Rubyèšèªã§èšè¿°ããã¡ãœããå ã§å®çŸããããšã¯ã§ããªããã®ã§ãããã?
ãããšããString#sub ãªã©ã®ããã«ã(Cèšèªãªã©ã®)Ruby
interpreterå®è£ èšèªã§çŽæ¥èšè¿°ãããããªãã®ã§ãããã?
ãã®ä»¶ã¯ãStackoverflow ã§è³ªåã¹ã¬ãããç«ãŠãŸããã
<https://stackoverflow.com/questions/52359278/how-to-pass-regexp-last-match-to-a-block-in-ruby/52385870>
åçããªãã£ãã®ã§ãäžå¿ãèªåèªèº«ã§ãäžå¯èœããšåçãããã§ãããã²ãã£ãšãããæ¹æ³ãããããç¥ããªããšããã¡ãã§è³ªåãã次第ã§ãã
äœããã³ãã§ãããã°ããããããé¡ãããŸãã
åéæ£æ
Rubyã®ã¡ãœããããããããã¯ã« $1, $2 (ãå«ãã
Regexp.last_match)
ãæž¡ãæ¹æ³ããªããã®ãããšè³ªåããŸãã
èæ¯ãšããŠã å éšã§ String#sub (gsub)
ãåŒã¶ãããªååã®(duck-typingã®)ã¡ãœãããäœã£ãŠããŸããåçŽåããäŸãæããŸãã
class C
# Stringã®ã€ã³ã¹ã¿ã³ã¹ str ã«å¯ŸããŠãsub() ãå®è¡
def self.sub(str, re, &b)
str.sub(re, &b)
end
end
/(prev)/ =~ 'previous'
p C.sub('baa', /(b)aa/){|a| a+'_'+$1}
# => "baa_prev" (âµ ãããã¯äžã§ ($1 == 'prev'))
# ãã㧠"baa_b" ãåŸãæ¹æ³ãããã?
Rubyã§ã¯ãäžè¬ã«ã$1
ã¯ãããŒã«ã«å€æ°ãšããŠæ±ããããšç解ããŠããŸããRuby
ã®ããŒã«ã«å€æ°ã¯ããããå²ãã¹ã³ãŒãã®å€æ°ãåŒãç¶ããŸããããããã£ãŠãäžã®äŸã§ã¯ãã¡ãœãã
C.sub ã«äžãããããã¯äžã«ãã $1
ã«ã¯ããã®ãããã¯ãå«ãæã®çŽåã®æ£èŠè¡šçŸè©äŸ¡ã®çµæ("prev")ãæž¡ã£ãŠããŸãã
ããããããã§è¡ãããããšã¯ããã¯ã©ã¹ C
ã®(ã¯ã©ã¹)ã¡ãœãã C.sub
ã§è©äŸ¡ãããæ£èŠè¡šçŸã®çµæãã $1
(ãªã©)ãšããŠãããã¯å ã§æ±ãããšã§ãã
çŸå®ã«ãString#sub
ãªã©ã§ã¯ãã¡ãœããå ã§æ£èŠè¡šçŸè©äŸ¡ããçµæã $1
(ãªã©)ãšããŠãããã¯ã«æž¡ãããŠããŠããã®ãããã¯ã®çµæãã¡ãœãã
sub() åŽãã yieldã§ããŠããŸãããããšåãããšã
Rubyèšèªã§èšè¿°ããã¡ãœããå ã§å®çŸããããšã¯ã§ããªããã®ã§ãããã?
ãããšããString#sub ãªã©ã®ããã«ã(Cèšèªãªã©ã®)Ruby
interpreterå®è£ èšèªã§çŽæ¥èšè¿°ãããããªãã®ã§ãããã?
ãã®ä»¶ã¯ãStackoverflow ã§è³ªåã¹ã¬ãããç«ãŠãŸããã
<https://stackoverflow.com/questions/52359278/how-to-pass-regexp-last-match-to-a-block-in-ruby/52385870>
åçããªãã£ãã®ã§ãäžå¿ãèªåèªèº«ã§ãäžå¯èœããšåçãããã§ãããã²ãã£ãšãããæ¹æ³ãããããç¥ããªããšããã¡ãã§è³ªåãã次第ã§ãã
äœããã³ãã§ãããã°ããããããé¡ãããŸãã
åéæ£æ