Tuesday, November 14, 2006

Pages 116-8: Including other files


Listen to this article.

Value: Medium

Level: Average

Summary:
As you split your code in multiple files, you can use two different methods to include it: load() or require(). The first reloads the file you need everytime you call it, the latter does it just once (usually).

Memo:
load() needs the file extension, while require() tries to add .rb to the filename.

Example:

This is the file included.rb

a = 1
def b
2
end

This is how require() works

a = "cat"
b = "dog"
require 'included'
puts a
puts b
b()
def b
puts 3
end
require 'included'
b()

This is how load() works

a = "cat"
b = "dog"
load 'included.rb'
puts a
puts b
b()
def b
puts 3
end
load 'included.rb'
b()

Doubts: 1
  • I was not able to understand the example for the load() method on page 118.
Reported errata (at 10/17/06 14:17:18 PDT): 0

Errata I found: 1
  • #2368: minor erratum.

My suggestions to the author: 6
  • Make clear that require() tries adding .rb to the filename, while load() doesn't.
  • Define what "shared binary libraries" are.
  • Make clear that also load() is an executable statements, as require() is.
  • Add "obviously" when stating that "local variables in a loaded or required file are not propagated to the scope that loads or requires them.". It's so obvious that could be misleading for a newbie.
  • Make clear that while local variables are not propagated, methods are.
  • Write a different example for the load() method. That one is way too contrived and impenetrable.

0 Comments:

Post a Comment

<< Home