What is the “sys.stdout.write()” equivalent in Ruby?

余生长醉 提交于 2019-12-03 14:38:23

问题


As seen in Python, what is the sys.stdout.write() equivalent in Ruby?


回答1:


In Ruby, you can access standard out with $stdout or STDOUT. So you can use the write method like this:

$stdout.write 'Hello, World!'

or equivalently:

STDOUT.write 'Hello, World!'

$stdout is a actually a global variable whose default value is STDOUT.

You could also use puts, but I think that is more analogous to python's print.




回答2:


puts (or print if you don't want a newline (\n) automatically appended).




回答3:


puts "Hello, world!"

or print - because it buffered.




回答4:


Here is a one liner for both writing and reading to/from stdin and stdout.

$ ruby -e '$stdout.write "hi\n" '
hi

$ echo "somestring" | ruby -e 'p  $stdin.read'
"somestring\n"

$ echo "somestring" | ruby -e 'puts   $stdin.read'
somestring


来源:https://stackoverflow.com/questions/3265129/what-is-the-sys-stdout-write-equivalent-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!