2010-08-25 66 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} 
相关问题