概要
String#self[nth] -> String | nil
String#slice(nth) -> String | nil
String#self[nth, len] -> String | nil
String#slice(nth, len) -> String | nil
詳細
nth 番目の文字を返却。
nth が正の場合: 文字列の先頭から数える
nth が負の場合: 文字列の末尾から数える
nth が範囲外の場合: nil を返却
サンプルコード
require 'tbpgr_utils' bulk_puts_eval binding, <<-EOS "123456789"[0] "123456789"[3] "123456789"[-1] "123456789"[-3] "123456789"[0, 3] "123456789"[3, 3] "123456789"[-1, 3] "123456789"[-3, 3] "123456789"[10] "-------------------------------" "123456789".slice(0) "123456789".slice(3) "123456789".slice(-1) "123456789".slice(-3) "123456789".slice(0, 3) "123456789".slice(3, 3) "123456789".slice(-1, 3) "123456789".slice(-3, 3) "123456789".slice(10) EOS __END__ 下記はTbpgrUtils gemの機能 bulk_puts_eval https://rubygems.org/gems/tbpgr_utils https://github.com/tbpgr/tbpgr_utils
出力
"123456789"[0] # => "1" "123456789"[3] # => "4" "123456789"[-1] # => "9" "123456789"[-3] # => "7" "123456789"[0, 3] # => "123" "123456789"[3, 3] # => "456" "123456789"[-1, 3] # => "9" "123456789"[-3, 3] # => "789" "123456789"[10] # => nil "-------------------------------" # => "-------------------------------" "123456789".slice(0) # => "1" "123456789".slice(3) # => "4" "123456789".slice(-1) # => "9" "123456789".slice(-3) # => "7" "123456789".slice(0, 3) # => "123" "123456789".slice(3, 3) # => "456" "123456789".slice(-1, 3) # => "9" "123456789".slice(-3, 3) # => "789" "123456789".slice(10) # => nil