Tbpgr Blog

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

Ruby | String | byteslice

概要

String#byteslice(nth) -> String | nil
String#byteslice(nth, len) -> String | nil
String#byteslice(range) -> String | nil

詳細

byte 単位での文字列切り出しを行う。

byteslice(nth) で任意の 1 byte
byteslice(nth, len) で任意の nth byte 目から len byte
byteslice(range) で range 範囲の byte

の切り出しにそれぞれ対応。

サンプルコード
require 'tbpgr_utils'


bulk_puts_eval binding, <<-EOS
'hoge'.byteslice(0)
'hoge'.byteslice(1)
'hoge'.byteslice(-1)
'hoge'.byteslice(1, 2)
'hoge'.byteslice(-2, 2)
'hoge'.byteslice(1..3)
'ほげ'.byteslice(0)
'ほげ'.byteslice(0, 2)
'ほげ'.byteslice(0..1)
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

'hoge'.byteslice(0)     # => "h"
'hoge'.byteslice(1)     # => "o"
'hoge'.byteslice(-1)    # => "e"
'hoge'.byteslice(1, 2)  # => "og"
'hoge'.byteslice(-2, 2) # => "ge"
'hoge'.byteslice(1..3)  # => "oge"
'ほげ'.byteslice(0)     # => "\xE3"
'ほげ'.byteslice(0, 2)  # => "\xE3\x81"
'ほげ'.byteslice(0..1)  # => "\xE3\x81"