0
0

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 1 year has passed since last update.

Ruby 文字の順番を入れ替えて出力するプログラム

Posted at

文字の順番を入れ替えて出力するプログラムを作成します

  • 条件1:任意の文字列の最初の2文字を取得する
  • 条件2:取得した2文字を最後尾に移動させた状態で、その文字列を出力する
def left2(str)
  puts str[2..-1] + str[0..1]
end
# 呼び出し例
left2("Hello")
# ターミナル
lloHe

解説

指定の文字列が何文字であっても対応できるようにコーディングしていく必要があります。

  • 最初の2文字はどのように取得するか
str[0..1]

[0..1]
0番目から始まるため、0~1と指定しています。

  • 最初の2文字を除いた残りの文字列はどのように取得するか?
    問題を解いていて考えたことは、最後の文字が何番目かということ。
    今回は「Hello」5文字ですが、何文字であってもプログラムとして成り立つように作らないといけません。
str[2..-1]

最後の文字を指定するには、-1と書きます。
以上で完成です!

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?