请解释 ruby ARGF 行为
ARGF.each_with_index do |line, idx|
print( "[#{idx}] #{line} x: " );
indent = Indent
# do stuff
indent = ""
end #ARGF e
如果您问我,STDIN 中的每一行都显示为“
x: [1] W:\sandbox\tmp\for_each\for_each.rake
这是不好 / 奇怪”。
另一个无法解释的结果是,该行...
print( "ab: [#{idx}] #{line} x: " );
显示:
x: ab: [1] W:\sandbox\tmp\for_each\for_each.rake
我在这里有一种奇怪的感觉。三个问题,这是:
- 如何“x:”字符串在每个“行”字符串的开头结束? ?!
- Ruby v1.8.7 的 bug 还是我的 bug?
- 如何修复它?
把招工广告。我一直看着这个,想知道我是否做了什么真正愚蠢的事情?非常感谢。
阿罗哈,威尔
ARGF.each_with_index do |line, idx|
print( "[#{idx}] #{line} x: " );
indent = Indent
# do stuff
indent = ""
end #ARGF e
Each line from STDIN is displayed as,
x: [1] W:\sandbox\tmp\for_each\for_each.rake
Which is not good / odd, if you ask me.
One further unexplained result, the line ...
print( "ab: [#{idx}] #{line} x: " );
Displays:
x: ab: [1] W:\sandbox\tmp\for_each\for_each.rake
I just get weird feelings here. Three questions, is this a:
- HOW does the "x:" string wind-up at the beginning of each 'line' the string??!
- Ruby v1.8.7 bug or my bug?
- How to fix it?
Help wanted. I keep looking at this and wonder if I what really dumb thing I did? Many thanks in advance.
aloha, Will
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
each_line
不会删除行末尾的换行符,因此each_line
生成的字符串将包含换行符。另一方面,print
不会在字符串末尾添加换行符(如果需要,请使用puts
)。因此,print "hello\nworld:
后跟print "lala"
将打印,这解释了为什么您的输出看起来像这样。
要获得您想要的输出,请使用 < code>line.chomp 而不是
line
,这将删除line
末尾的换行符,从而防止字符串在之前包含换行符>x:。
each_line
does not remove the newlines at the end of the lines, so the strings yielded byeach_line
will contain newlines.print
on the other hand will not add newlines to the end of strings (if you want that, useputs
). Soprint "hello\nworld:
followed byprint "lala"
, will printwhich explains why your output looks the way it does.
To get the output you want, use
line.chomp
instead ofline
, which will remove the newline at the end ofline
and thus prevent your strings from containing a line break beforex:
.这里有点抱歉。我fergot有关 Windows 上的行尾和 CR/LF 问题。解决方案似乎是:
打印以下行:
对于年轻玩家来说,剩下的陷阱是在 chomp!() 方法之后放置您自己的换行符(\n)。我犯的一个错误是认为“trim()”而不是“chomp()”——我有多疯狂。
干杯,
A small sorry here. I fergot about end of line and CR/LF issues on Windows. The solution seems to be:
Which prints the line:
The remaining trap for young players, is to put your own newline(\n) after the chomp!() method. One mistake I made with this was thinking 'trim()' not 'chomp()' -- How crazy are I.
Cheers,