简体   繁体   中英

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)

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.

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.

IO doesn't have a 'built in' write method. File.write should do this job

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM