Read the Ruby line one character at a time (for word wrap)

I know this question is fundamental. I can take user input for a string and for an integer using:

str = gets() num = gets().to_i 

But I want to read the String character (say, which is in my case more than the length of the string) by the character and count the number of characters from the first to the last for each character that appears in the string. I know that this can be achieved by:

str.length

I want to find it characteristic, because I'm trying to implement word wrapping in Ruby, which says that within the line width (which would be the number entered by the user), I would like to print only those words that do not continue until the next line, i.e. . I do not want to split a continuous word into two lines. Such words should be translated in a new line.

Thank you for your time..!!

+6
input ruby user-input
source share
2 answers

getc will read in the character at a time:

 char = getc() 

Or you can each_char over characters in a string using each_char :

 'abc'.each_char do |char| puts char end 
+7
source share

You might want to check Text :: Format . In addition, Rails has word_wrap as part of the ActionView, and Padrino has similar word_wrap if you are creating web material.

Otherwise, this is a sample string from: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/249306

 str = "\ I don't necessarily need code examples -- but if anyone has ideas for a best approach to specifying a line wrap width (breaking between words for lines no longer than a specific column width) for output from a Ruby script, I'd love to hear about it." X = 40 puts str.gsub(/\n/," ").scan(/\S.{0,#{X-2}}\S(?=\s|$)|\S+/) --- output --- I don't necessarily need code examples -- but if anyone has ideas for a best approach to specifying a line wrap width (breaking between words for lines no longer than a specific column width) for output from a Ruby script, I'd love to hear about it. 
+5
source share

All Articles