2

我有一个简单的 Ruby 脚本,它将为我在文本文件中“大写”标题。这是脚本:

$ 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

如果我将文件名传递给它,它工作正常:

$ 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)"

但我也希望能够像这样运行脚本:

$ cat lowercase | capitalize.rb

或者即使这样也可以:

$ cat lowercase | capitalize.rb -

但我收到这些错误消息:

$ 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

我需要在脚本中进行哪些更改?

谢谢!

编辑 :

这是回答这个问题的脚本:

$ 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

感谢和+感谢所有回复的人。

4

1 回答 1

0

我认为你可以做这样简单的事情:

if ARGV.length == 0
  file = STDIN
else
  file = File.new( ARGV[0] , "r")
end
于 2013-09-01T03:21:20.440 回答