Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Regexp | try_convert

概要

Regexp#try_convert(obj) -> Regexp | nil

詳細

obj を to_regexp メソッドRegexp オブジェクトに変換する。
成功すれば Regexp を返却。
失敗時は nil を返却。

サンプルコード
require 'tbpgr_utils'

class DuckTypeRegexp
  def initialize(pattern)
    @pattern = pattern
  end

  def to_regexp
    /#{@pattern}/
  end
end

bulk_puts_eval binding, <<-EOS
Regexp.try_convert(/h.ge/)
Regexp.try_convert("h.ge")
Regexp.try_convert(DuckTypeRegexp.new("h.ge"))
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

Regexp.try_convert(/h.ge/)                     # => /h.ge/
Regexp.try_convert("h.ge")                     # => nil
Regexp.try_convert(DuckTypeRegexp.new("h.ge")) # => /h.ge/