Programming Ruby: The Pragmatic Programmers' Guide

Programming Ruby: The Pragmatic Programmers' Guide
Author: David Thomas; Chad Fowler; Andrew Hunt
Language: eng
Format: mobi
Tags: Non-fiction, COMPUTERS / Programming Languages / Ruby, Reference
ISBN: 9780974514055
Publisher: Pragmatic Bookshelf
Published: 2000-12-15

# this can be mixed in but the variable x won't be visible

def no_bar

return x

end

def bar

@x = 1000

return @x

end

puts( "In Foo: x = #{x}" ) # this can access the module-local x

end

include Foo # mix in the Foo module

When you run this program, the puts method executes when the module is initialized, and it displays the value of the module-local variable x:

In Foo: x = 50

If you display the x variable within the main scope of the program, the value of the variable x local to the main scope of the program is used, not the value of the variable x local to the module:

puts(x) #=> 1

But any attempt to execute the no_bar method will fail:

puts( no_bar ) # Error: undefined local variable or method 'x'

Here the no_bar method is unable to access either of the local variables named x even though x is declared both in the scope of the module (x = 50) and in the current or “main” scope (x = 1). But there is no such problem with instance variables. The bar method is able to return the value of the instance variable @x:

puts(bar) #=> 1000

A module may have its own instance variables that belong exclusively to the module “object.” These instance variables will be in scope to a module method:

inst_class_vars.rb

module X

@instvar = "X's @instvar"