나는 ShaneQful의 반응이 좋다 @이 코드를 사용하기 때문에 생각하지만 그는 이것이하는 일은이 file_name
문자열로를 판독 열립니다
file_name = "D:/test.txt"
old_color = "white"
new_color = "black"
File.write(file_name,File.open(file_name,&:read).gsub(old_color,new_color))
에 훨씬 더 쉽게이을 진술 할 수있다. old_color
의 모든 인스턴스를 new_color
으로 바꾸고 (#gsub
) file_name
에 다시 씁니다.
간단하고 쉽고 깨끗하며 간결합니다. 이
(ShaneQful의 예에서와 같이)
업데이트
벤치마킹의 File#read
, File.open(file_name,&:read)
및 File.open with block read into a string and then written back to file_name
는 ~ 포함 잭 런던의 화이트 팡에 75,000 단어와 단어의 645 개 인스턴스를 벤치마킹했다 white
#Benchmark
Rehearsal --------------------------------------------------------
File#read 0.375000 0.484000 0.859000 ( 1.462000)
File.open(&:read) 0.437000 0.530000 0.967000 ( 1.480000)
File.open with block 1.404000 0.359000 1.763000 ( 2.150000)
----------------------------------------------- total: 3.589000sec
user system total real
File#read 0.452000 0.499000 0.951000 ( 1.401000)
File.open(&:read) 0.483000 0.421000 0.904000 ( 1.445000)
File.open with block 1.529000 0.328000 1.857000 ( 2.120000)
#Fruity
Running each test 2 times. Test will take about 3 minutes.
File.open(&:read) is similar to File#read
File#read is faster than File.open with block by 50.0% ± 10.0%
File#read
및으로 보입니다.구현 속도는 앞뒤가 맞지만 동일한 작업을 처리하기 위해 실제 블록을 사용하면 항상 이러한 유형의 작업이 훨씬 느립니다.
이 간단한 절차를위한 종관은 read
또는 #open(file_name,&:read)
(Symbol#to_proc
)입니다. 여러 라인이나 조건부 옵션을 취할 수있는 정교한 변경을 수행해야한다면 블록을 사용할 것입니다.
시도'puts line.sub (oldcolor, newcolor) ' –
그게 효과가! . 이제 같은 파일 내에서 변경 사항을 저장하려고합니다. –
파일을 현재 위치에서 변경할 수 없습니다. 대신 디스크에서 메모리로 읽어 와서 변경 한 후 다시 써야합니다. – Stefan