2010-08-25 67 views
6

我在寫的Ruby的方法找到一個文本如何在Ruby中查找字符串的所有循環?

x = "ABCDE" 
(x.length).times do 
    puts x 
    x = x[1..x.length] + x[0].chr 
end 

有沒有實現這一種更好的方式的所有圓形組合?

+0

「更好」是什麼意思? – 2010-08-25 19:22:25

+0

我的意思是已經存在的方法? – bragboy 2010-08-25 19:24:59

回答

11

這是另一種方法。

str = "ABCDE" 
(0...str.length).collect { |i| (str * 2)[i, str.length] } 

我用了一個範圍,#collect與你要做些別的事情與字符串(不只是打印出來)的假設。

+0

完美!這正是我正在尋找的掃管笏。 – bragboy 2010-08-25 19:35:27

+0

'(str * 2)[i,str.length]'帶我幾個讓我聽到。但後來我意識到這是天才。好的解決方案 – 2010-08-25 19:36:15

4

我會做這樣的事情:

x = "ABCDE" 
x.length.downto(0) do |i| 
    puts x[i..-1] + x[0...i] 
end 

它加到從目前指數的字符串到年底,開始時到當前的指數。

這樣你根本不需要改變你的原始變量。

+0

謝謝Squeegy,我也喜歡你的解決方案! – wuputah 2010-08-25 19:38:41

2

將字符串合併到自身,並使用Enumerable.each_cons獲取大小爲n的所有連續元素(n是原始字符串的長度)。

s = "hello" 
(s + s).split('').each_cons(s.size).map(&:join)[0..-2] 

# ["hello", "elloh", "llohe", "lohel", "ohell"] 
+0

細微變化:(s * 2).split('')。each_cons(s.size).map(&:join)[0 ..- 2] 不需要做uniq只是爲了剪掉最後一個字符串在數組中。 – 2010-08-25 19:50:08

+0

謝謝@Vijay,這是一個很好的優化 – Anurag 2010-08-25 19:59:14

3

你可以寫一個枚舉器。

#!/usr/bin/env ruby 

class String 
    def rotations 
    Enumerator.new do|y| 
     times = 0 
     chars = split('') 

     begin 
     y.yield chars.join('') 

     chars.push chars.shift 
     times += 1 
     end while times < chars.length 
    end 
    end 
end 

這樣你就可以做這樣的事情。

"test".rotations.each {|r| puts r} 
相關問題