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.

1
  • Thanks Andrew. I got my answer for that post. I guess my question is a duplicate then. Commented Sep 1, 2013 at 3:38

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.