【问题标题】:Why does ruby's IO.read add a newline?为什么 ruby​​ 的 IO.read 添加换行符?
【发布时间】:2018-09-21 23:32:37
【问题描述】:
$ echo testing > testfile
$ irb
2.5.1 :001 > IO.read('testfile')
=> "testing\n"

试图了解换行符的来源,因为它显然不在文件中。

【问题讨论】:

  • "试图了解换行符的来源,因为它显然不在文件中。" ——你是如何确定“明显不在档案中”的?根据您发布的命令,除非您的 echo 已损坏,否则文件中“显然”应该有一个换行符。
  • 我的测试是在 vim 中打开它,但这还不够好。显然,我的回声按记录运行。 #PEBKAC

标签: ruby io


【解决方案1】:

但换行符在文件中,echo 添加它。您可以使用 hexdump 自己查看:

$ echo testing > testfile
$ hexdump testfile 
0000000 74 65 73 74 69 6e 67 0a                        
0000008

0x0a 是你的换行符。

你可以向你的shell(大概是bash)询问echo

$ help echo
echo: echo [-neE] [arg ...]
    Output the ARGs.  If -n is specified, the trailing newline is
    suppressed. [...]

所以如果你说echo -n testing > testfile,你会得到你期望的结果。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 2018-08-30
  • 2013-07-14
  • 2021-03-10
  • 2013-08-07
相关资源
最近更新 更多