Avatar

This is my first attempt of file I/O in Ruby(1.8.6). As you can tell from the block comments, it is limited and error-prone. I am aware of exception handling, however I can't seem to implement it correctly when using keywords like `raise'. Any help on re-factoring and even extending functionality would be very much appreciated.

1
2
3
4
5
6
7
parameter, file, text = ARGV

if parameter == '-w' #=> write mode
    File.open(file, 'w'){ text }
if parameter == '-r' #=> read mode
    File.readlines(file).each{ text }
end

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Example 1:
$ ./file.rb -w /home/usr/hello.rb "puts 'hello, world'"
$ ./file.rb -r /home/usr/hello.rb
puts 'hello, world'

Example 2:
$ ./file.rb -w /home/usr/hello.rb "puts "hello, world""
$ ./file.rb -r /home/usr/hello.rb
puts hello

Example 3:
$ ./file.rb -w /home/usr/hello.rb "puts 'hello, world!'"
bash: !: event not found

Example 4:
$ ./file.rb -w /home/usr/hello.rb "puts 'hello, world\!'"
$ ./file.rb -r /home/usr/hello.rb 
puts 'hello, world\!'

Refactorings

No refactoring yet !

Ee0505bbd355292778077fb662c88f13

Fu86

June 21, 2010, June 21, 2010 00:35, permalink

No rating. Login to rate!

The Problem with parameters is that your shell handles the parameter substitution. If you write ... *.mp3, your shell will substitute this to a list of filenames ending with .mp3. This behavior differs in some shells. The last example (4) with the ! works great (without the \) on my zsh shell.

You can work with pipes to avoid this problems.

Catch all parameters

1
all_params = $*

Use Pipes

1
puts gets unless STDIN.eof?

Example

1
2
echo "puts 'Hello World'" | ./file.rb
cat data.txt | ./file.rb

Your refactoring





Format Copy from initial code

or Cancel