cande
cande

Reputation: 35

Ruby undefined method `write' for IO:Class (NoMethodError)

when i run my ruby file

ruby test.rb

which has one line:

IO.write("testfile.txt","123")

i get

test.rb:1:in `<main>': undefined method `write' for IO:Class (NoMethodError)

Upvotes: 2

Views: 4574

Answers (2)

Dominik Honnef
Dominik Honnef

Reputation: 18430

Well, what kind of answer do you expect? IO does not have any class method called write. At most it has binwrite and an instance method #write.

So either you use binwrite (http://rubydoc.info/stdlib/core/1.9.3/IO.binwrite) or you use the File class and go the full way of

File.open("testfile.txt", "w") { |f| f << "123" }

Edit: Apparently there is an IO.write method beginning with Ruby 1.9.3. There is, however, no such method in any earlier versions of 1.9 or 1.8.

Upvotes: 3

Moiz Raja
Moiz Raja

Reputation: 5762

There are a couple of issues,

  1. IO does not have a class method write and that it why you are seeing the exception
  2. If you want to write to a file you should use the File class

    File.open("testfile.txt", "w") do |file| file.write("123") end

I think you're probably just getting started with Ruby so it may be a good idea to read up a book on ruby which will show some of these basics. I have used "The Ruby Programming Language" by David Flanagan and Matz, but quite a few people have used what is called the Pickaxe book or "Programming Ruby" by Dave Thomas, Chad Fowler and Andy Hunt.

Upvotes: 0

Related Questions