given a string of digits, output all the contiguous substrings of length n in that string in the order that they appear. in ruby

You can achieve this in Ruby by using the each_cons method of the Enumerable module to generate all the contiguous substrings of length n from a given string.

Here's a code example:

main.rb
def output_substrings(string, n)
  substrings = string.each_char.each_cons(n).map(&:join)
  puts substrings
end

# Example usage
output_substrings("1234567890", 3)
164 chars
8 lines

In the code above, the each_char method is used to iterate over each character of the string. The each_cons method is then used to generate consecutive arrays of n characters, which are then mapped to join them into substrings.

Running the example code with the string "1234567890" and n as 3 will output all the contiguous substrings of length 3 in the order they appear:

main.rb
123
234
345
456
567
678
789
890
32 chars
9 lines

Note that if the length n is greater than the length of the string, it will not output anything.

gistlibby LogSnag