Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all cycles of a String in Ruby?

Tags:

string

ruby

I have written a method in Ruby to find all the circular combination of a text

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

Is there a better way to implement this ?

like image 826
bragboy Avatar asked Aug 25 '10 19:08

bragboy


1 Answers

Here's an alternative approach.

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

I used a range and #collect with the assumption that you'll want to do something else with the strings (not just print them).

like image 69
wuputah Avatar answered Nov 04 '22 12:11

wuputah