I decided to implement properly the Code Golf challenge about twisting strings. I report the assignement verbatim for convenience:
Twisting Words!
Given a string and a positive integer. You must twist the string, back and forth.
Example Input / Output
Input
Programming Puzzles & Code Golf 4
Output
Prog mmar ing zzuP les oC & de G flo
Input
The input can be taken in through STDIN, or function argument. The input will consist of a string and a positive integer, n. The integer will determine the length of each twisted line.
The string is twisted back-and-forth. An input of
HELLO, WORLD!
and 5 would look like:
Output
The output will be the twisted text. It may not any trailing whitespace. If the input string length is not divisible be the line length, add a space until the line is filled:
An example of this: Input
Hello, World! 5
Output (Note the whitespace at the very end)
Hello roW , ld!
My implementation
def twist(text, chunk_size)
text
.+(" " * ((text.length % chunk_size) - 1))
.chars
.each_slice(chunk_size)
.each_with_index
.map {|str, i| i.odd? ? str.reverse : str}
.map(&:join)
.join("\n")
end
puts twist("Hello, World!", 5)
puts
puts twist("foo bar baz", 7)