0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby | If you use a variable in a regular expression conditional expression, you can not assign a variable by named capture

Last updated at Posted at 2019-04-16

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

About this translattion

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?