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 に答える