1 Answer
1

Ruby has a method each_cons(n). In your code, you can write word_array.each_cons(2) do |current_word, next_word|.

There is a bug in the code where you write wrapped_words << current_word[@wrap_column..-1]. This assumes that a word can be broken only once. For example, WordWrap.new(3).wrap("wordword") will return "wor\ndword".

Extending the above logic, the next block adding a new line in the case next_word is not nil is also a bug. Consider the input "word w" when you have to wrap on 3 columns. Your output will be "wor\nd\nw" whereas the correct output should be "wor\nd w".

I'll not be adding any more code comments since you seem to have some pretty serious bugs in your code owing to all those conditions. What I do recommend is to revise your strategy. Try thinking along these lines for a pretty solution:

Scan the input string one character at a time.

Remember the current length of scan.

Remember the position of the last space seen every time you encounter a space.

If the current length of the scan is equal to the wrap value, it's time to take action based on the position of the last space seen:

If it's not nil, you have to copy everything up to that position into the result string plus a new line. Reset the current_length based on how much was copied.

If it's nil, copy everything up to the current index and then add a new line.

Reset the position of the last space seen to nil.

If it's the end of string and your result string has a new line at the end, chomp it off.

\$\begingroup\$Thanks Chandranshu. I've redone the exercise using your suggestions of examining every character and I like that solution much better. Very clean and readable. I'm always amazed at how changing a single assumption can so drastically effect the result.\$\endgroup\$
– user341493Jan 8 '14 at 18:49