一次读取一个字符的 Ruby 字符串(用于自动换行)
我知道这个问题是一个基本问题。我可以使用以下命令获取字符串和整数的用户输入:
str = gets()
num = gets().to_i
但我想从字符串(比如在我的例子中长度超过一行)中逐个字符读取并计算第一个字符的数量到字符串中遇到的每个字符的最后一个。我知道这可以通过以下方式实现:
字符串长度
我想按字符计数,因为我试图在 Ruby 中实现自动换行,其中在行宽(这将是用户定义的数字输入)内我只想打印那些不继续到下一行的单词,即我不想将连续的单词分成两行。这些话应该换到新的一行。
谢谢你的时间..!!
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..!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getc
将在 a 处读入一个字符time:或者您可以使用
each_char
循环遍历字符串中的字符:getc
will read in a character at a time:Or you can cycle through the characters in the string with
each_char
:您可能想查看 Text::Format gem。此外,Rails 还具有 word_wrap 作为 ActionView 的一部分,并且 Padrino 有一个类似的 word_wrap 方法,如果你'正在做网络方面的事情。
否则,这是来自以下位置的换行示例: http:// /blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/249306
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