SlideShare una empresa de Scribd logo
1 de 12
Descargar para leer sin conexión
Railsのhelperでnamed
capture使ったらハマった話
chezou
kawasaki.rb #010
正規表現とnamed capture
• 正規表現のグループに名前をつけて、後方参
照できる
pat = /(?<good>good|nice|greate) catch/!
#=> /(?<good>good|nice|greate) catch/!
pat === 'nice catch!!'!
#=> true!
Regexp.last_match!
#=> #<MatchData "nice catch" good:"nice">!
Regexp.last_match[:good]!
#=> "nice"!
helperでnamed capture
• Railsのhelperでnamed capture使ったgsubした
ら…
module FooHelper!
def replace_awesome(str)!
str.gsub(pat){|m| "#{m}!!!" if Regexp.last_match[:good]}!
end!
end!
!
- str = 'nice catch'!
= replace_awesome(str) #=> "nice catch!!!"!
# こういうのがやりたい!
現実
= replace_awesome(str)!
NoMethodError: undefined method `[]' for nil:NilClass
( д) ゚ ゚
なぜだろう?
=> ActiveSupport::SafeBuffer
module FooHelper!
def replace_awesome(str)!
p(str.class) !
str.gsub(pat){|m| "#{m}!!!" if Regexp.last_match[:good]}!
end!
end!
AS::SafeBufferとは
• RailsのviewではHTMLの特殊文字(<,>,&,")を自
動的にエスケープしてくれる
• その時に出力されるクラスがAS::SafeBuffer
"".html_safe + "<" #=> "&lt;"!
("".html_safe + "<").class #=> ActiveSupport::SafeBuffer!
http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-string
SafeBufferのgsubを見た
rails/activesupport/lib/active_support/core_ext/string/output_safety.rb
module ActiveSupport!
  class SafeBuffer < String!
    UNSAFE_STRING_METHODS = %w(!
capitalize chomp chop delete downcase gsub lstrip next reverse rstrip!
slice squeeze strip sub succ swapcase tr tr_s upcase prepend!
)!
…!
    UNSAFE_STRING_METHODS.each do |unsafe_method|!
      if unsafe_method.respond_to?(unsafe_method)!
        class_eval <<-EOT, __FILE__, __LINE__ + 1!
def #{unsafe_method}(*args, &block) # def capitalize(*args, &block)!
to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)!
end # end!
!
def #{unsafe_method}!(*args) # def capitalize!(*args)!
@html_safe = false # @html_safe = false!
super # super!
end # end!
EOT!
      end!
    end!
Rubyのみの再現コード
def test(*args, &block)!
'hogehoge'.gsub(/h/, &block)!
p Regexp.last_match!
end!
 !
test do |matched|!
p Regexp.last_match!
end!
Rubyのみの再現コード
def test(*args, &block)!
'hogehoge'.gsub(/h/, &block)!
p Regexp.last_match #=> <MatchData "h">!
end!
 !
test do |matched|!
p Regexp.last_match #=> nil!
end!
仕様です
Rubyのみの再現コード
def test(*args, &block)!
'hogehoge'.gsub(/h/, &block)!
p Regexp.last_match #=> <MatchData "h">!
end!
 !
test do |matched|!
p Regexp.last_match #=> nil!
end!
block内のscopeと違うので取れません
回避方法
module FooHelper!
def replace_awesome(str)!
str.to_str.gsub(pat){|m| "#{m}!!!" if $~[:good]}!
end!
end!
 !
- str = 'nice catch'!
= replace_awesome(str) #=> "nice catch!!!"!

Más contenido relacionado

Más de Aki Ariga

Challenges for machine learning systems toward continuous improvement
Challenges for machine learning systems toward continuous improvementChallenges for machine learning systems toward continuous improvement
Challenges for machine learning systems toward continuous improvementAki Ariga
 
Managing Machine Learning workflows on Treasure Data
Managing Machine Learning workflows on Treasure DataManaging Machine Learning workflows on Treasure Data
Managing Machine Learning workflows on Treasure DataAki Ariga
 
仕事ではじめる機械学習
仕事ではじめる機械学習仕事ではじめる機械学習
仕事ではじめる機械学習Aki Ariga
 
主人が外資系IT企業に転職して4ヶ月が過ぎました
主人が外資系IT企業に転職して4ヶ月が過ぎました主人が外資系IT企業に転職して4ヶ月が過ぎました
主人が外資系IT企業に転職して4ヶ月が過ぎましたAki Ariga
 
R&D at Foodtech company - #CookpadTechConf 2016
R&D at Foodtech company - #CookpadTechConf 2016R&D at Foodtech company - #CookpadTechConf 2016
R&D at Foodtech company - #CookpadTechConf 2016Aki Ariga
 
Why I started Machine Learning Casual Talks? #MLCT
Why I started Machine Learning Casual Talks? #MLCTWhy I started Machine Learning Casual Talks? #MLCT
Why I started Machine Learning Casual Talks? #MLCTAki Ariga
 
クックパッドサマーインターン2015 機械学習・自然言語処理 実習課題
クックパッドサマーインターン2015 機械学習・自然言語処理 実習課題クックパッドサマーインターン2015 機械学習・自然言語処理 実習課題
クックパッドサマーインターン2015 機械学習・自然言語処理 実習課題Aki Ariga
 
Rubyistがgemの前にPypiデビューするのは間違っているだろうか
Rubyistがgemの前にPypiデビューするのは間違っているだろうかRubyistがgemの前にPypiデビューするのは間違っているだろうか
Rubyistがgemの前にPypiデビューするのは間違っているだろうかAki Ariga
 
Machine Learning Casual Talks Intro #MLCT
Machine Learning Casual Talks Intro #MLCTMachine Learning Casual Talks Intro #MLCT
Machine Learning Casual Talks Intro #MLCTAki Ariga
 
Make Julia more popular in Japan!!1 #JuliaTokyo
Make Julia more popular in Japan!!1 #JuliaTokyoMake Julia more popular in Japan!!1 #JuliaTokyo
Make Julia more popular in Japan!!1 #JuliaTokyoAki Ariga
 
Refrection of kawasaki.rb
Refrection of kawasaki.rbRefrection of kawasaki.rb
Refrection of kawasaki.rbAki Ariga
 
Introduction and benchmarking of MeCab.jl #JapanR
Introduction and benchmarking of MeCab.jl  #JapanRIntroduction and benchmarking of MeCab.jl  #JapanR
Introduction and benchmarking of MeCab.jl #JapanRAki Ariga
 
Recommendation for iruby #tqrk08
Recommendation for iruby #tqrk08Recommendation for iruby #tqrk08
Recommendation for iruby #tqrk08Aki Ariga
 
The book that changed me
The book that changed meThe book that changed me
The book that changed meAki Ariga
 
Introduction of Mecab.jl #JuliaTokyo
Introduction of Mecab.jl #JuliaTokyoIntroduction of Mecab.jl #JuliaTokyo
Introduction of Mecab.jl #JuliaTokyoAki Ariga
 
Machine Learning Casual Talks opening talk
Machine Learning Casual Talks opening talkMachine Learning Casual Talks opening talk
Machine Learning Casual Talks opening talkAki Ariga
 
なぜ科学計算にはPythonか?
なぜ科学計算にはPythonか?なぜ科学計算にはPythonか?
なぜ科学計算にはPythonか?Aki Ariga
 
Active ModelとNaive Bayesを仲良くする
baby_faceを使ってみた
Active ModelとNaive Bayesを仲良くする
baby_faceを使ってみたActive ModelとNaive Bayesを仲良くする
baby_faceを使ってみた
Active ModelとNaive Bayesを仲良くする
baby_faceを使ってみたAki Ariga
 
Rubyと機械学習の現状
Rubyと機械学習の現状Rubyと機械学習の現状
Rubyと機械学習の現状Aki Ariga
 

Más de Aki Ariga (19)

Challenges for machine learning systems toward continuous improvement
Challenges for machine learning systems toward continuous improvementChallenges for machine learning systems toward continuous improvement
Challenges for machine learning systems toward continuous improvement
 
Managing Machine Learning workflows on Treasure Data
Managing Machine Learning workflows on Treasure DataManaging Machine Learning workflows on Treasure Data
Managing Machine Learning workflows on Treasure Data
 
仕事ではじめる機械学習
仕事ではじめる機械学習仕事ではじめる機械学習
仕事ではじめる機械学習
 
主人が外資系IT企業に転職して4ヶ月が過ぎました
主人が外資系IT企業に転職して4ヶ月が過ぎました主人が外資系IT企業に転職して4ヶ月が過ぎました
主人が外資系IT企業に転職して4ヶ月が過ぎました
 
R&D at Foodtech company - #CookpadTechConf 2016
R&D at Foodtech company - #CookpadTechConf 2016R&D at Foodtech company - #CookpadTechConf 2016
R&D at Foodtech company - #CookpadTechConf 2016
 
Why I started Machine Learning Casual Talks? #MLCT
Why I started Machine Learning Casual Talks? #MLCTWhy I started Machine Learning Casual Talks? #MLCT
Why I started Machine Learning Casual Talks? #MLCT
 
クックパッドサマーインターン2015 機械学習・自然言語処理 実習課題
クックパッドサマーインターン2015 機械学習・自然言語処理 実習課題クックパッドサマーインターン2015 機械学習・自然言語処理 実習課題
クックパッドサマーインターン2015 機械学習・自然言語処理 実習課題
 
Rubyistがgemの前にPypiデビューするのは間違っているだろうか
Rubyistがgemの前にPypiデビューするのは間違っているだろうかRubyistがgemの前にPypiデビューするのは間違っているだろうか
Rubyistがgemの前にPypiデビューするのは間違っているだろうか
 
Machine Learning Casual Talks Intro #MLCT
Machine Learning Casual Talks Intro #MLCTMachine Learning Casual Talks Intro #MLCT
Machine Learning Casual Talks Intro #MLCT
 
Make Julia more popular in Japan!!1 #JuliaTokyo
Make Julia more popular in Japan!!1 #JuliaTokyoMake Julia more popular in Japan!!1 #JuliaTokyo
Make Julia more popular in Japan!!1 #JuliaTokyo
 
Refrection of kawasaki.rb
Refrection of kawasaki.rbRefrection of kawasaki.rb
Refrection of kawasaki.rb
 
Introduction and benchmarking of MeCab.jl #JapanR
Introduction and benchmarking of MeCab.jl  #JapanRIntroduction and benchmarking of MeCab.jl  #JapanR
Introduction and benchmarking of MeCab.jl #JapanR
 
Recommendation for iruby #tqrk08
Recommendation for iruby #tqrk08Recommendation for iruby #tqrk08
Recommendation for iruby #tqrk08
 
The book that changed me
The book that changed meThe book that changed me
The book that changed me
 
Introduction of Mecab.jl #JuliaTokyo
Introduction of Mecab.jl #JuliaTokyoIntroduction of Mecab.jl #JuliaTokyo
Introduction of Mecab.jl #JuliaTokyo
 
Machine Learning Casual Talks opening talk
Machine Learning Casual Talks opening talkMachine Learning Casual Talks opening talk
Machine Learning Casual Talks opening talk
 
なぜ科学計算にはPythonか?
なぜ科学計算にはPythonか?なぜ科学計算にはPythonか?
なぜ科学計算にはPythonか?
 
Active ModelとNaive Bayesを仲良くする
baby_faceを使ってみた
Active ModelとNaive Bayesを仲良くする
baby_faceを使ってみたActive ModelとNaive Bayesを仲良くする
baby_faceを使ってみた
Active ModelとNaive Bayesを仲良くする
baby_faceを使ってみた
 
Rubyと機械学習の現状
Rubyと機械学習の現状Rubyと機械学習の現状
Rubyと機械学習の現状
 

Último

TSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdfTSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdftaisei2219
 
Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Danieldanielhu54
 
論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A surveyToru Tamaki
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムsugiuralab
 
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Yuma Ohgami
 
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...Toru Tamaki
 
論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNetToru Tamaki
 
SOPを理解する 2024/04/19 の勉強会で発表されたものです
SOPを理解する       2024/04/19 の勉強会で発表されたものですSOPを理解する       2024/04/19 の勉強会で発表されたものです
SOPを理解する 2024/04/19 の勉強会で発表されたものですiPride Co., Ltd.
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略Ryo Sasaki
 
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)Hiroki Ichikura
 

Último (10)

TSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdfTSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdf
 
Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Daniel
 
論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システム
 
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
 
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
 
論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet
 
SOPを理解する 2024/04/19 の勉強会で発表されたものです
SOPを理解する       2024/04/19 の勉強会で発表されたものですSOPを理解する       2024/04/19 の勉強会で発表されたものです
SOPを理解する 2024/04/19 の勉強会で発表されたものです
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
 
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
 

gsub with ActiveSupport::SafeBuffer