Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

8
  • Thanks for the detailed answer, Luke. The way you wrote it is close to the way it was written in the example. I was wondering if the do...end - the {...} in your example - and the code-block in between is even necessary. For example, can't you just write: File.write yourfile 'w' It seems like you're saying that's not correct. Commented Mar 20, 2014 at 0:25
  • Well you can't write in a file using File.write yourfile 'w'. Here is the irb output for such a statment: >> File.write 'test.txt', "Hi there" NoMethodError: undefined method 'write' for File:Class You first need to open the file to access the stream and write in it. You can try yourself in irb. Commented Mar 20, 2014 at 0:58
  • @LukeS, what do you mean it doesn't work? File.write 'file', 'data', mode: 'a' works here and in a couple sites I used to test. Commented Mar 20, 2014 at 1:06
  • @LukeS Sorry, I wrote down my example incorrectly. File.write 'yourfile', string ---> Instead of File.write yourfile 'w'. Commented Mar 20, 2014 at 1:06
  • My answer gives you the good practice, one line way to write to a file. Note that .open is a synonym for ::new File.open Commented Mar 20, 2014 at 1:07