Ruby 5-2

こんにちは!

今日は一段と暑い。。。

文字列の操作

具体的に色々なメソッドを確認していきます。

str_len.rb
Image from Gyazo

Image from Gyazo

文字列の長さを取得します。
エイリアス(Alias)とはメソッドの別名で、今回のsizeメソッドはlengthメソッドのエイリアスです。

str_empty.rb
Image from Gyazo

Image from Gyazo

空文字列の確認にはempty?メソッドを利用します。
空白だけの文字列の判定にはstripを利用します。

str_case.rb
Image from Gyazo

Image from Gyazo

大文字と小文字を変換するメソッドです。

str_case2.rb
Image from Gyazo

Image from Gyazo

戻り値として返す代わりにレシーバーに書き戻す、downcase!などを破壊的メソッドと言います。

str_case_ignore.rb
Image from Gyazo

Image from Gyazo

「==」演算子は大文字と小文字を区別します。

str_slice.rb
Image from Gyazo

Image from Gyazo

sliceメソッドの主な結果です。

str_slice2.rb
Image from Gyazo

Image from Gyazo

slice!メソッドを用いると、元の文字列から除去できます。

str_bracket.rb
Image from Gyazo

Image from Gyazo

sliceメソッドの省略構文、ブラケット構文です。

str_bracket2.rb
Image from Gyazo

Image from Gyazo

ブラケット構文を用いることで、文字列の一部を置換や削除可能です。

str_index.rb
Image from Gyazo

Image from Gyazo

文字列を前方から検索するindexメソッド、後方から検索するrindexメソッドです。

str_concat.rb
Image from Gyazo

Image from Gyazo

文字列を追加するconcatメソッドです。
元の文字列も変更されています。

str_plus.rb
Image from Gyazo

Image from Gyazo

+演算子を用いると、元の文字列を変更せずに新たな文字列を作成します。

str_strip.rb
Image from Gyazo

Image from Gyazo

前後双方の空白を除去するstripメソッド、前方だけを除去するlstripメソッド、後方だけを除去するrstripメソッドです。
空白にはタブや改行なども含まれます。

str_chomp.rb
Image from Gyazo

Image from Gyazo

末尾の改行を除去するchompメソッドです。
空文字を指定すると、末尾に連続するすべての改行文字を除去します。

str_chop.rb
Image from Gyazo

Image from Gyazo

空白や改行文字に限らず、任意の末尾文字を除去するchopメソッドです。

str_delete.rb
Image from Gyazo

Image from Gyazo

指定された文字列を先頭や末尾から除去するdeleteメソッドです。

str_include.rb
Image from Gyazo

Image from Gyazo

特定の文字列が含まれているかを判定するinclude?メソッドなどがあります。

str_split.rb
Image from Gyazo

Image from Gyazo

splitメソッドで特定の区切りを表現します。
色々なパターンを確認しています。

str_split_block.rb
Image from Gyazo

Image from Gyazo

splitメソッドをブロックに渡すことでループ処理が可能になります。

str_each_char.rb
Image from Gyazo

Image from Gyazo

each_charメソッドを用いて文字単位の分割が可能です。

str_lines.rb
Image from Gyazo

Image from Gyazo

改行文字に特化したlinesメソッドです。
こちらも色々なパターンを確認しています。

str_lines_each.rb
Image from Gyazo

Image from Gyazo

分割した各行を処理するeach_lineメソッドです。

str_partition.rb
Image from Gyazo

Image from Gyazo

最初に見つけた位置で分割するpartitionメソッド、最後で分割するrpartitionメソッドです。
文字が見つからなかったり、区切り文字が空の場合は空白を返します。

str_encode.rb
Image from Gyazo

Image from Gyazo

環境依存文字など表示できない文字を置換させています。

最後に文字列の整形です。
ややこしいので、一旦確認のみにしておきます。

str_format.rb
Image from Gyazo

Image from Gyazo

理解には実践あるのみ。

ではでは。