Ruby에서 STDIN을 사용한 모범 사례?
Ruby의 명령줄 입력을 처리하고 싶습니다.
> cat input.txt | myprog.rb
> myprog.rb < input.txt
> myprog.rb arg1 arg2 arg3 ...
그것을 하는 가장 좋은 방법은 무엇입니까?특히 blank STDIN을 다루고 싶고, 우아한 해결책을 원합니다.
#!/usr/bin/env ruby
STDIN.read.split("\n").each do |a|
puts a
end
ARGV.each do |b|
puts b
end
다음은 제가 수집한 무명의 루비에서 발견한 것들입니다.
no-bell 인 서이현구명령의간단한어닉래그스는유.
cat다음과 같습니다.#!/usr/bin/env ruby puts ARGF.readhttps://web.archive.org/web/20080725055721/http ://www.oreillynet.com/ruby/blog/2007/04/trivial_scripting_with_ruby.html#comment-565558
ARGF 이름이 지정된 파일 또는 STDIN에서 모든 입력을 가져오는 가상 파일입니다.
ARGF.each_with_index do |line, idx|
print ARGF.filename, ":", idx, ";", line
end
# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
puts line if line =~ /login/
end
이지만, 루에서다이몬교드구환못하만다지행우, 리는받니다습았이비해지아을원▁thank▁get▁did다▁in▁operator▁but▁we니받우▁the▁we▁didn▁ruby루습았,리,비▁diamond▁goodness는만'▁gett.
ARGF실제로.분명치는 않지만, 실제로 유용한 것으로 밝혀졌습니다. Perlism에) .-i합니다.#!/usr/bin/env ruby -i Header = DATA.read ARGF.each_line do |e| puts Header if ARGF.pos - e.length == 0 puts e end __END__ #-- # Copyright (C) 2007 Fancypants, Inc. #++— http://blog.nicksieger.com/articles/2007/10/06/obscure-and-ugly-perlisms-in-ruby
신용 거래처:
- https://web.archive.org/web/20080725055721/http ://www.oreillynet.com/ruby/blog/2007/04/trivial_scripting_with_ruby.html#comment-565558
- http://blog.nicksieger.com/articles/2007/10/06/obscure-and-ugly-perlisms-in-ruby
Ruby는 STDIN을 처리하는 또 다른 방법을 제공합니다.-n 플래그.명령행 인수로 전달된 파일을 포함하여 전체 프로그램이 STDIN을 통해 루프 안에 있는 것으로 간주됩니다.예: 다음 1줄 스크립트를 참조하십시오.
#!/usr/bin/env ruby -n
#example.rb
puts "hello: #{$_}" #prepend 'hello:' to each line from STDIN
#these will all work:
# ./example.rb < input.txt
# cat input.txt | ./example.rb
# ./example.rb input.txt
무엇이 필요한지 잘 모르겠지만, 다음과 같은 것을 사용할 것입니다.
#!/usr/bin/env ruby
until ARGV.empty? do
puts "From arguments: #{ARGV.shift}"
end
while a = gets
puts "From stdin: #{a}"
end
ARGV 배열이 처음 시작하기 전에 비어 있기 때문에 주의하십시오.getsRuby는 인수를 읽을 텍스트 파일(Perl에서 상속된 동작)로 해석하려고 하지 않습니다.
stdin이 비어 있거나 인수가 없으면 아무것도 인쇄되지 않습니다.
몇 가지 테스트 사례:
$ cat input.txt | ./myprog.rb
From stdin: line 1
From stdin: line 2
$ ./myprog.rb arg1 arg2 arg3
From arguments: arg1
From arguments: arg2
From arguments: arg3
hi!
From stdin: hi!
이런 거?
#/usr/bin/env ruby
if $stdin.tty?
ARGV.each do |file|
puts "do something with this file: #{file}"
end
else
$stdin.each_line do |line|
puts "do something with this line: #{line}"
end
end
예:
> cat input.txt | ./myprog.rb
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb < input.txt
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb arg1 arg2 arg3
do something with this file: arg1
do something with this file: arg2
do something with this file: arg3
while STDIN.gets
puts $_
end
while ARGF.gets
puts $_
end
이는 Perl에서 영감을 얻은 것입니다.
while(<STDIN>){
print "$_\n"
}
빠르고 단순:
STDIN.gets.chomp == 'YES'
사용할 수도 있습니다.STDIN.each_line,그리고.STDIN.each_line.to_a배열로 가져올 수 있습니다.
예.
STDIN.each_line do |line|
puts line
end
사용하기 위해 추가하겠습니다.ARGF매개 변수를 사용하여 삭제해야 합니다.ARGV부르기 전에ARGF.each그 이유는ARGF의 모든 것을 치료할 것입니다.ARGV파일 이름으로 먼저 줄을 읽습니다.
다음은 'tee' 구현의 예입니다.
File.open(ARGV[0], 'w') do |file|
ARGV.clear
ARGF.each do |line|
puts line
file.write(line)
end
end
저는 다음과 같은 일을 합니다.
all_lines = ""
ARGV.each do |line|
all_lines << line + "\n"
end
puts all_lines
대부분의 답변은 인수가 stdin에 전달될 내용을 포함하는 파일 이름이라고 가정하는 것 같습니다.아래의 모든 것은 단순한 주장으로 취급됩니다.STDIN이 TTY의 것이면 무시됩니다.
$ cat tstarg.rb
while a=(ARGV.shift or (!STDIN.tty? and STDIN.gets) )
puts a
end
인수 또는 stdin은 비어 있거나 데이터가 있을 수 있습니다.
$ cat numbers
1
2
3
4
5
$ ./tstarg.rb a b c < numbers
a
b
c
1
2
3
4
5
언급URL : https://stackoverflow.com/questions/273262/best-practices-with-stdin-in-ruby
'programing' 카테고리의 다른 글
| 루비에서 사용되지 않는 코드를 표시하는 모범 사례? (0) | 2023.06.04 |
|---|---|
| 아이템을 유지하는 방법새로 인스턴스화된 스피너에 대한 발사에서 선택되었습니까? (0) | 2023.06.04 |
| 코코아 포드가 macOS High Sierra에서 작동하지 않음 (0) | 2023.06.04 |
| Xcode 4.2 및 iOS 5 SDK를 사용할 때 이전 iOS 버전을 대상으로 하는 것이 가능합니까? (0) | 2023.06.04 |
| 스위프트 앱에 로컬 데이터를 저장하는 방법은 무엇입니까? (0) | 2023.06.04 |