user782220
user782220

Reputation: 11187

How is File.open implemented in Ruby?

I tried finding how File.open() was implemented but I couldn't find it while grepping around in the code I got from https://github.com/ruby/ruby

Upvotes: 0

Views: 259

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369438

There is no File::open, it is inherited from IO. So, you need to look for IO::open.

In general, I recommend using the Rubinius source code for this. It is much better organized and much better documented than YARV's source code, and most importantly: it is mostly written in Ruby, whereas in YARV the entire language, the entire core library and significant portions of the standard library are written in C.

That being said, the implementation of IO::open is completely and utterly boring. It just does the obvious thing:

def self.open(*args)
  io = new(*args)

  return io unless block_given?

  begin
    yield io
  ensure
    begin
      io.close unless io.closed?
    rescue StandardError
      # nothing, just swallow them.
    end
  end
end

Upvotes: 0

cHao
cHao

Reputation: 86506

The File class is a C module, not a Ruby one. So, you won't find Ruby code for it.

Looks like it lives in file.c in the root folder. The module includes the IO module, which is another C module and lives in io.c in the same location. Look for functions in there whose names start with rb_file_open.

Upvotes: 1

Related Questions