2017-05-02 12 views
0
input_file = ARGV.first 

def print_all(f) 
    puts f.read 
end 

def rewind(f) 
    f.seek(0) 
end 

def print_a_line(line_count, f) 
    puts "#{line_count}, #{f.gets.chomp}" 
end 

current_file = open(input_file) 

puts "First let's print the whole file:¥n" 

print_all(current_file) 

puts "Let's rewind kind a like a tape" 

rewind(current_file) 

puts "Let's print three lines:" 

current_line = 1 
print_a_line(current_line, current_file) 

current_line += 1 
print_a_line(current_line, current_file) 

나는 이와 비슷한 게시물이있을 것이라고 확신하지만 내 질문은 약간 다릅니다. 위에서 보듯이 print_a_line 메소드에는 line_count와 f 인 두 개의 매개 변수가 있습니다.gets.chomp를 인수로 전달

1) 알다시피, line_count 인수는 current_line 인 변수로만 사용되며 정수입니다. I 코드를 실행할 때, 상기 방법 print_a_line 이것을 나타내고 있기 때문에 되감기 (f)의 방법에 관한 않는 방법

1은 첫 번째 행이며, 2 번째 인
1, Hi 
2, I'm a noob 

. line_count는 숫자 일뿐입니다. 루비는 1이 1 행이고 2가 2 행이라는 것을 어떻게 알 수 있습니까?

2) print_a_line 메서드에서 gets.chomp를 사용하는 이유는 무엇입니까? 나는이

def print_a_line(line_count, f) 
    puts "#{line_count}, #{f}" 
end 

처럼 미친 결과를 얻을 수 있습니다 단지 f를 전달하는 경우 IO#gets 읽을 I/O 스트림 (이 경우에는 파일의)과에서 다음 줄을 읽기 때문에하는

1, #<File:0x007fccef84c4c0> 
2, #<File:0x007fccef84c4c0> 

답변

0

입니다 성공적으로 읽을 때 파일의 끝에 도달하지 않을 때 String 개체를 반환합니다. 그리고 chompString 개체에서 캐리지 리턴 문자를 제거합니다. 당신이 같은 내용을 가진 파일이있을 때

그래서 :

This is file content. 
This file has multiple lines. 

을 코드가 인쇄됩니다 : 두 번째 경우

1, This is file content. 
2, This file has multiple lines. 

을, 당신은 파일 객체 자체를 전달하고 그것을 읽는하지 않을 . 따라서 출력물에있는 객체를 볼 수 있습니다.