2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rubyで文字列を反転させる(reverseあり・なし)

Posted at

Rubyで文字列を反転させるプログラムを書きます。

reverse.rb
str = "123456789"
reversed_str = ""
str_size = str.length.to_i

while str_size > 0 do
  reversed_str << str[str_size - 1]
  str_size -= 1
end

puts str
puts reversed_str
実行結果
$ruby reverse.rb
123456789
987654321

また、Rubyの組み込みライブラリを使っても出来ます。

String#reverse
文字列を文字単位で左右逆転した文字列を返します。

p "foobar".reverse   # => "raboof"
p "".reverse         # => ""

参考:String#reverse (Ruby 3.0.0 リファレンスマニュアル)

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?