How to find all row loops in Ruby?

I wrote a method in Ruby to find the whole circular combination of 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?

+6
string ruby
source share
4 answers

Here's an alternative approach.

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

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

+11
source share

I would do something like this:

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

It concatenates the row from the current index to the end, starting from the current index.

Thus, you do not need to modify the original variable at all.

+4
source share

You can write an enumerator.

 #!/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 

That way you can do such things.

 "test".rotations.each {|r| puts r} 
+3
source share

Combine the string with yourself and get all consecutive elements of size n (n is the length of the original string) using Enumerable.each_cons .

 s = "hello" (s + s).split('').each_cons(s.size).map(&:join)[0..-2] # ["hello", "elloh", "llohe", "lohel", "ohell"] 
+2
source share

All Articles