basic action
If you use named capture with a regular expression (a person with a conditional expression on the left side ). A value is assigned to a local variable.
/a (?<month>July)/ =~ 'Ruby is a July birth stone' month # => "July"
problem
However. Using variables in match conditions does not create local variables.
a = 'a' /#{a} (?<month>July)/ =~ 'Ruby is a July birth stone' # => 8 month #=> #<NameError: undefined local variable or method `month' for main:Object>
The match itself is successful. The variable month
does not exist.
Solution
Even in the same way. #match
can capture normally by using the #match
method.
a = 'a' 'Ruby is a July birth stone'.match(/#{a} (?<month>July)/) { |matched| matched[:month] } # => July
How nice!
However, in the case of #match
. Local variable month
can not be created. If you really want to make it, you should assign it to the return value.
a = 'a' month = 'Ruby is a July birth stone'.match(/#{a} (?<month>July)/) { |matched| matched[:month] } month # => "July"
Note
There is also a problem with the #match
method. It is fine if it is the above writing method. Be careful if you use capture results in other ways.
Ruby | We cope with NoMethodError when it does not match in regular expression capture
environment
- Ruby 2.2.4
Original by
Ruby | 正規表現の条件式に変数を使うと、名前付きキャプチャによる変数代入が出来ない
About
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。