2

I have a simple Ruby script that will "capitalize" titles in a text file for me. Here's the script:

$ cat capitalize.rb
#!/usr/bin/ruby -w

file = File.new( ARGV[0] , "r")
while (line = file.gets)
        #line.capitalize!
        ine = line.split(" ").map {|word| word.capitalize}.join(" ")
        puts "\t\t,\t\"#{ine}\""
end
file.close

It works fine if I pass it the name of a file:

$ cat lowercase
come back with me (Ep. 0301)
murder will out (Ep. 0302)
snake in the grass (Ep. 0308)
goodbye carl erich (Ep. 0309)
nightmares nest (Ep. 0310)
$ capitalize.rb lowercase
                ,       "Come Back With Me (ep. 0301)"
                ,       "Murder Will Out (ep. 0302)"
                ,       "Snake In The Grass (ep. 0308)"
                ,       "Goodbye Carl Erich (ep. 0309)"
                ,       "Nightmares Nest (ep. 0310)"

But I would like to be able to run the script like this also:

$ cat lowercase | capitalize.rb

Or even this would be fine:

$ cat lowercase | capitalize.rb -

But I get these error messages:

$ cat lowercase | capitalize.rb
/home/red/scripts/capitalize.rb:5:in `initialize': can't convert nil into String (TypeError)
        from /home/red/scripts/capitalize.rb:5:in `new'
        from /home/red/scripts/capitalize.rb:5
$ cat lowercase | capitalize.rb -
/home/red/scripts/capitalize.rb:5:in `initialize': No such file or directory - - (Errno::ENOENT)
        from /home/red/scripts/capitalize.rb:5:in `new'
        from /home/red/scripts/capitalize.rb:5

What do I need to change in my script?

Thanks!

Edit :

Here is the script that answers this question:

$ cat scripts/capitalize.rb
#!/usr/bin/ruby -w

ARGF.each do |line|
        ine = line.split(" ").map {|word| word.capitalize}.join(" ")
        puts "\t\t,\t\"#{ine}\""
end

Thanks and + to everyone that responded.

Red Cricket
  • 9,762
  • 21
  • 81
  • 166

1 Answers1

0

I think you can do something as simple as this:

if ARGV.length == 0
  file = STDIN
else
  file = File.new( ARGV[0] , "r")
end
  • 1
    I'd recommend reading through the linked answers marking this question as a duplicate. Ruby's built-in `ARGF` is the right way to go about doing this. – the Tin Man Sep 01 '13 at 03:46