Rubyで文字列を反転(リバース)するサンプルコード等を以下に記します。
htmlinsert(): The given local file does not exist or is not readable.
$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 12.04.4 LTS Release: 12.04 Codename: precise
以下にreverseメソッドを使用したサンプルコードを記します。
s = "LL.JUST4FUN.BIZ" puts "\"#{s}\".reverse : " + s.reverse
上記のコードを実行したときの出力です。
"LL.JUST4FUN.BIZ".reverse : ZIB.NUF4TSUJ.LL
破壊的なメソッドを使用したサンプルコードを以下に記します。 reverse, reverse!を使用したサンプルコードを以下に記します。
s = "LL.JUST4FUN.BIZ" puts "\"#{s}\".reverse : " + s.reverse puts "s = #{s}" puts "\"#{s}\".reverse! : " + s.reverse! puts "s = #{s}"
上記のサンプルコードを実行した時の出力です。
"LL.JUST4FUN.BIZ".reverse : ZIB.NUF4TSUJ.LL s = LL.JUST4FUN.BIZ "LL.JUST4FUN.BIZ".reverse! : ZIB.NUF4TSUJ.LL s = ZIB.NUF4TSUJ.LL
reverseを使用した場合、文字列が格納されているsには変化はありません。
しかし、reverse!を使用すると文字列が格納されているsの文字列値が反転(リバース)されているのが確認できます。
以上、reverse, reverse!による文字列反転のサンプルコードでした。