루비에서 파일에 쓰는 가장 좋은 방법은 무엇입니까? [닫은

StackOverflow https://stackoverflow.com/questions/150731

  •  02-07-2019
  •  | 
  •  

문제

루비의 파일에 데이터를 작성하고 싶습니다. 그렇게하는 가장 좋은 방법은 무엇입니까?

도움이 되었습니까?

해결책

File.open("a_file", "w") do |f|
    f.write "some data"
end

당신은 또한 사용할 수 있습니다 f << "some data" 또는 f.puts "some data" 신축성을 갖는 개인적인 취향/필요성에 따라. 변경 "w" 에게 "a" 각 열린마다 잘라내는 대신 파일에 추가하려면.

다른 팁

require 'rio'
rio('foo.txt') < 'bar'

http://rio.rubyforge.org/

그 너머에 file.new 또는 file.open (그리고 다른 모든 재미있는 IO 재료) 특히 루비로 저장하고 다시로드하는 경우 데이터에 사용되는 경우, 육군 원수 객체를 직접 저장하고로드합니다.

Using File::open is the best way to go:

File.open("/path/to/file", "w") do |file|
  file.puts "Hello file!"
end

As previously stated, you can use "a" instead of "w" to append to the file. May other modes are available, listed under ri IO, or at the Ruby Quickref.

filey = File.new("/path/to/the/file", APPEND)
filey.puts "stuff to write"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top