gpt4 book ai didi

ruby - 请解释 ruby​​ ARGF 行为

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:57 25 4
gpt4 key购买 nike

   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

我只是在这里有一种奇怪的感觉。三个问题,is this a:

  1. 如何在每个“”字符串的开头处结束“x:”字符串??!<
  2. Ruby v1.8.7 错误还是我的错误?
  3. 如何解决?

需要帮助。我一直看着这个,想知道我是否做了什么真正愚蠢的事情?非常感谢。

你好,威尔

最佳答案

each_line 不会删除行尾的换行符,因此 each_line 生成的字符串将包含换行符。另一方面,print 不会在字符串末尾添加换行符(如果需要,请使用 puts)。所以 print "hello\nworld: 然后是 print "lala",将打印

hello
world:lala

这解释了为什么你的输出看起来是这样的。

要获得所需的输出,请使用 line.chomp 而不是 line,这将删除 line 末尾的换行符和从而防止您的字符串在 x: 之前包含换行符。

关于ruby - 请解释 ruby​​ ARGF 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4830115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com