我有一个简单的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
感谢并回复了所有回复的人。
答案 0 :(得分:0)
我认为你可以做一些简单的事情:
if ARGV.length == 0
file = STDIN
else
file = File.new( ARGV[0] , "r")
end