🔖

IO#puts の挙動

2023/08/07に公開

まとめ

  • 末尾が "\n"(0x0a) でない場合、暗黙に "\n" を足す。

動作確認

Rails Console で書き込みをする

irb(main):029:0> f = File.open("1rn.txt",'w+b')
=> #<File:1rn.txt>
irb(main):031:0> f.puts "1\r\n"
=> nil
irb(main):032:0> f.close
=> nil
irb(main):033:0> f = File.open("1r.txt",'w+b')
=> #<File:1r.txt>
irb(main):034:0> f.puts "1\r"
=> nil
irb(main):035:0> f.close
=> nil
irb(main):036:0> f = File.open("1n.txt",'w+b')
=> #<File:1n.txt>
irb(main):037:0> f.puts "1\n"
=> nil
irb(main):038:0> f.close
=> nil
irb(main):039:0> f = File.open("1.txt",'w+b')
=> #<File:1.txt>
irb(main):040:0> f.puts "1"
=> nil
irb(main):041:0> f.close
=> nil

書き込みされたファイルを確認する

❯  xxd 1rn.txt
00000000: 310d 0a                                  1..
❯  xxd 1r.txt
00000000: 310d 0a                                  1..
❯  xxd 1n.txt
00000000: 310a                                     1.
❯  xxd 1.txt
00000000: 310a                                     1.

→ "1\r" や "1" だけ書き込んだ場合 "\n" が足されている
→ "\n" で終わっている場合は足されてない

ソースコード

  • File#puts は IO を継承

https://docs.ruby-lang.org/ja/latest/class/File.html

IO から継承しているメソッド
puts

  • IO#puts

https://github.com/ruby/ruby/blob/master/io.c#L15366

putsrb_f_puts によって define される

https://github.com/ruby/ruby/blob/11f33ba6204909ebbb142283bc9395d3343db28e/io.c#L8951-L8958

標準出力に書き出す場合 rb_io_puts が呼ばれる

https://github.com/ruby/ruby/blob/11f33ba6204909ebbb142283bc9395d3343db28e/io.c#L8928-L8933

line が "\n" で終わってない場合、line のさらに後に rb_default_rs が足される

https://github.com/ruby/ruby/blob/master/io.c#L15447

rb_default_rs は "\n"

終わり □

GitHubで編集を提案

Discussion