Basic IO


Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents

Basic I/O

The puts method is closest to Python's print statement, since it adds a new line. Ruby's print adds the default record separator, which is usually nil. The puts method uses the result of inspect, whereas the other two use to_s. The inspect method is like Python's repr() function, and to_s is like str(). As we mentioned, backticks in Ruby are used as a shortcut for exec to run shell commands.

For input, use gets. Here is an imitation of raw_input:


 def raw_input(prompt="")  print prompt  gets end x = raw_input("Please enter a number: ") 

File handling is very similar to Python's approach. Open files are closed during garbage collection (GC) if they are no longer referenced. But if you use the block form of, then Ruby will close the file for you at the end of the block without waiting for GC to occur."somefile") do |f|  f.puts "#{} : line added to file" end  # File object f is now closed 

This do/end is actually another syntax form of the iterator block.




The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: