Tbpgr Blog

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

Ruby | String | try_convert

概要

String.try_convert(obj) -> String | nil

詳細

obj を String に変換を試行。
変換には Object#to_str メソッドが使われる。

変換成功時: 変換後文字列
変換失敗時: nil

サンプルコード
require 'tbpgr_utils'

class Convertable
  def to_str
    "converted"
  end
end

bulk_puts_eval binding, <<-EOS
String.try_convert(1)
String.try_convert(Convertable.new)
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

String.try_convert(1)               # => nil
String.try_convert(Convertable.new) # => "converted"