Ruby Koans で学ぶ String
Stringはわかってるだろ・・とタカをくくってました;;
%記法
通常のダブル・シングルクオートで囲むのが難しい(そいつらが大量に出てくる文字列等)のために、別の記号でクオートできる方法があった。
a = %(flexible quotes can handle both ' and " characters) b = %!flexible quotes can handle both ' and " characters! c = %{flexible quotes can handle both ' and " characters}
%の後に置いた記号のペアで囲まれた箇所を、Stringオブジェクトにしてくれる記法。
英語では"flexible quotes"、日本語では%記法と呼ぶらしい。
%記法は複数行になってもよい
long_string = %{ It was the best of times, It was the worst of times. }
- long_string.length => 全部の文字数取得
- long_string.lines => 各行を文字列の配列で取得
- long_string.lines.count => 3行
- 一文字目は改行文字
ヒアドキュメントと似てるけど・・違いは
- %記法で複数行の場合、%{の行から1行目になる
- ヒアドキュメントの場合、開始ラベルの次の行が1行目になる
long_string = <<EOS It was the best of times, It was the worst of times. EOS
- long_string.lines.count => 2行
- 一文字目は"I"
文字列の連結方法
+で連結
+連結は非破壊的
original_string = "Hello, " hi = original_string there = "World" hi += there assert_equal "Hello, ", original_string
original_stringそのまま。
<<で連結
<<連結は破壊的
original_string = "Hello, " hi = original_string there = "World" hi << there assert_equal "Hello, World", original_string
original_string連結後の文字列になってる。
Question : +より<<が好まれる傾向があるけど、何故か?
コレ、詳しい。
<<の場合元の文字列のメモリサイズが、文字を連結しても大丈夫ならばそのままつっこむ。らしい。 メモリを新たに確保していないので、元の文字列に破壊的に操作していくことになる。
なるほど〜
文字列の分割
- split デフォルトでスペース分割
string = "Sausage Egg Cheese" words = string.split assert_equal ["Sausage", "Egg", "Cheese"], words
- 分割方法を正規表現で指定可能
例:コロンで分割
words = string.split(/:/)
文字列の比較
- ==比較では文字列の字面で比較
- 別々の文字列リテラルの場合、object_idは別々