Input / Output / File Handling in Ruby

Getting input from STDIO:

	>> puts "please input some string"
	>> name = gets

	>> puts "The string is " + name

	>> name = gets.chomp
	>> name = gets.chomp.downcase
	>> name = gets.chomp.to_i 
Opening and Closing Files

Create a data file in Linux using "vi" editor or NotePad in Win

$vi input.txt

Type some five lines of text and then press escape followed by :wq to save the file

In ruby you need to define a filehandle to point to the input file

	>> filehandle = File.new  "input.txt"  {in windows C:\\Directory\\input.txt }
	>> filehandle.readlines.each do |item|
	>> puts item
	>> end
	...{if you get no output, use filehandle.rewind and retry do loop}
	>> filehandle.close
File Handling ...

Another way to open a file -

	>> File.open("foo.txt") do |filehandle|
	# do something with file
	>> end
Example
	>> File.open("input.txt") do |filehandle|
	>> filehandle.readlines.each do |item|
	>> puts item
	>> end
	>> end
File Access permissions

	>> outputfilehandle = File.new "output.txt", "w"   {Write Mode}
	>> logfilehandle = File.new "logfile.txt", "a"    {Append Mode}

	>> outputfilehandle.write "We are trying to write into a file\n"
	>> logfilehandle.write "This line will be appended\n"
Reserved words in Ruby - you can't use these words as variables

alias and BEGIN begin break case class def defined do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield

Go to ruby-page 6 ... Back to ruby-page 4 ... Starting page 1