LoginSignup
0
0

More than 1 year has passed since last update.

Ruby 文字列の順番を変える

Posted at

Rubyで勉強したことをアウトプットします。

やりたいこと

  • 任意の文字列の最初の2文字を取得する
  • 取得した2文字を最後尾に移動させた状態で、その文字列を出力する

最初に作成したコード

def change_str(str)
  first_str = str[0]  
  second_str = str[1]
  len = str.length
  arr = []
  (2..len).each do |num|
    arr << str[num]
  end
  puts "#{arr.join}#{first_str}#{second_str}"
end

change_str("Hello")
# >> "lloHe"

joinメソッド

joinメソッドを使用することで、配列内の要素を文字列として連結することができます。

# 配列を宣言
arr = ['a', 'b', 'c']

# 配列の要素を連結して文字列として返却します  
p arr.join
# >> 'abc'

引数を指定すると、要素ごとに引数の文字列を結合することができます。

# 配列を宣言
arr = ['a', 'b', 'c']

# 配列の要素を連結して文字列として返却します  
p arr.join(":")
# >> 'a:b:c'

改善後のコード

def change_str(str)
  puts str[2..-1] + str[0..1]  
end

left2("Hello") 
# >> "lloHe"

今回の勉強で、配列の操作方法について学びました。

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