Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a Ruby string one character at a time (for word wrapping)

I know this question is a fundamental one. I am able to take user input for a string and for an integer using:

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

But I want to read from the String(say which is in my case more than a line in length) character by character and count the number of characters from the first to the very last for every character encountered in the string. I know this can be achieved through:

str.length

I want to count it character wise as I am trying to implement word wrap in Ruby, wherein say within the line width(which would be a user defined number input) I would want to print only those words which are not continuing over to the next line i.e. I don't want to split a continuous word over two lines. Such words should be taken to the new line.

Thanks for you time..!!

like image 328
boddhisattva Avatar asked Dec 23 '10 01:12

boddhisattva


2 Answers

getc will read in a character at a time:

char = getc()

Or you can cycle through the characters in the string with each_char:

'abc'.each_char do |char|
  puts char
end  
like image 71
bowsersenior Avatar answered Oct 05 '22 20:10

bowsersenior


You might want to check out the Text::Format gem. Also, Rails has word_wrap as part of ActionView, and Padrino has a similar word_wrap method if you're doing web stuff.

Otherwise this is a linewrap sample 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.
like image 24
the Tin Man Avatar answered Oct 05 '22 19:10

the Tin Man