Help us understand the problem. What is going on with this article?

文字列を回転させる

More than 1 year has passed since last update.

文字列回転

こういう文字列が欲しい時があるかもしれません

  • 1234なら

    • 1234, 2341, 3412, 4123
  • helloなら

    • hello,elloh,llohe,lohel,ohell

こんな感じで書いてみた

def rolling(str)
  arr = str.to_s.split("")
  ans = []
  for i in 0...arr.length
    ans << arr[i...arr.length].concat(arr[0...i]).flatten
  end
  ans
end

def rolling_str(s)
  rolling(s).map{|arr| arr.join.to_s}
end

def rolling_num(n)
  rolling(n).map{|arr| arr.join.to_i}
end

テスト

p rolling_num(1234)
[1234, 2341, 3412, 4123]
p rolling_str("hello")

["hello", "elloh", "llohe", "lohel", "ohell"]

EDIT

@jnchito さんからコメントがありました。Array自体に#rotateというメソッドが生えているので、それを使ったほうが良さそうです。コメント欄参照。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away