Re: Question regarding interaction between modules and classes

Get uting @@foo instead of @foo

Sent from my HTC

----- Reply message -----
From: “Geometric Patterns” [email protected]
To: [email protected]
Subject: Question regarding interaction between modules and classes
Date: Sun, May 8, 2011 05:02


In the code below, is there a way to learn @foo from $bar_one
using $bar_two?

Many thanks in advance!!

#!/usr/bin/ruby -w

module Foo
def setup
@foo = self.object_id
def foo
return @foo

class Bar
include Foo

$bar_one =
p $ # => 2148224640

$bar_two =
p $ # => warning: instance variable @foo not initialized

On Sun, May 8, 2011 at 11:03 AM, [email protected] [email protected] wrote:

Get uting @@foo instead of @foo

Better: Don’t use class variables. If there’s a @@foo somewhere in the
ancestry tree of a module or class, this one will be used, instead of
what you set @@foo to in your own class.

A class method works much better:

class Klass
@foo = “foo”
def # note the self receiver. Very important!
=> “foo”

To get @foo from another class:

class KlassTwo
@foo = # Klass has to be defined before KlassTwo, obviously.

Phillip G.

Though the folk I have met,
(Ah, how soon!) they forget
When I’ve moved on to some other place,
There may be one or two,
When I’ve played and passed through,
Who’ll remember my song or my face.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs