2010-01-06 1 views

답변

18

처음 다섯 줄을 완전히 제거 할 수 있습니다. 곡괭이

에서

따라서

$<: An object that provides access to the concatenation of the contents of all the files given as command-line arguments or $stdin (in the case where there are no arguments). $< supports methods similar to a File object: binmode, close, closed?, each, each_byte, each_line, eof, eof?, file, filename, fileno, getc, gets, lineno, lineno=, path, pos, pos=, read, readchar, readline, readlines, rewind, seek, skip, tell, to_a, to_i, to_io, to_s, along with the methods in Enumerable. The method file returns a File object for the file currently being read. This may change as $< reads through the files on the command line. [r/o]

:

print $<.read 

Kernel.gets 그렇게 $ < .gets 속기이다 :

while s = gets 
    puts s 
end 
+2

으로 업데이트되었습니다. 또한'$ <'의 별명이기 때문에'ARGF'를 사용할 수 있습니다. – kejadlen

+0

예 - 멋지 네요. 왜 이걸 잡으려고 서클에서 처음으로 원을 돌았는지 궁금합니다. 아마도 그것은 (루비 myscript.rb 'args없이 스크립트를 실행하면 약간 이상한 (하지만 좋은) 행동 때문에 생각, 스크립트가 단순히 종료 - 대부분의 프로그램 (물론 유닉스에서 인스턴스에 대한) 앉아서 기다릴 것입니다 stdin : 그래서 거기에 뭔가를 구현해야한다고 생각했는데 실제로 (설명을 주셔서 감사합니다) Ruby 인터프리터는 뭔가 유용하고 매우 영리합니다 (평소와 같이)! 감사합니다. . – monojohnny

+0

나는 당신과 함께 거기에있다. 나는이 모든 작은 루비 트릭에 여전히 익숙해 져있다. –

2

then;

은 또한 당신이 삼항 연산자를 사용할 수있는 선택 사항입니다 에 File(), 그래서

input = ARGV ? $< : File.new(ARGV[0]) 
+0

대 - 한 -하지만 난 투표 다른 답변은 더 짧습니다! 좋은 루비! – monojohnny

3

ARGV ? 작품, "r" 일반적으로 너무 기본이 그것을 건너 뛸 수 있고, File.new()가 동일 할 수 있습니다

if (ARGV[0].nil?) then 
    input=$< 
else 
    input=File.new(ARGV[0],"r"); 
end 

... 
# Do something with the input here, for example: 
input.each_line do |line| 
    puts line 
end 
+0

이 사람처럼 : 감사합니다! – monojohnny

+0

+1, 멋지다 File() : – makevoid

+0

파일 ("foo")이 더 이상 작동하지 않는 것 같습니다 (루비 2.3.1) : NoMethodError : 정의되지 않은 메소드 File : main : Object. –

관련 문제