Thanks, I think this will do the trick! Unfortunately it just brings up more
questions than answers.
How can you define instance variables inside of a class method? Who is self?
The class object. What is the difference between a classes' instance
variables and an object's class variables. I tried the following code and it
failed to execute.
class Bob
def Bob.test
attr_reader :test1
@test1 = 1
end
def test2
p self.class.inspect
p self.class.test1.inspect
end
end
Bob.test
bob = Bob.new
bob.test2
produced:
"Bob"
bob.rb:9:in `test2': undefined method `test1' for Bob:Class (NameError)
from bob.rb:15
Does your code work because it is executing in the context of a class
definition, where self is the class being defined?
Thanks for all your help.
Steve Tuckner :>>
-----Original Message-----
From: matz / zetabits.com [mailto:matz / zetabits.com]
Sent: Monday, June 18, 2001 11:01 PM
To: ruby-talk / ruby-lang.org
Subject: [ruby-talk:16616] Re: Class Var question
Hi,
In message "[ruby-talk:16610] Re: Class Var question"
on 01/06/19, Steve Tuckner <SAT / MULTITECH.com> writes:
|What I want to do is have some "meta" information about an object's
members.
|So for example if an object has two members: ht and wt, I want to
associated
|with them the names to display if I have an object display module. I would
|like to use the following code to use this capability.
<snip>
Is the following code close to what you want?
----
class Object
def Object.uservar(name, printname)
@user_vars ||= {}
@user_vars[name] = printname
attr_reader name
end
def Object.uservars
if defined? @user_vars
@user_vars
else
{}
end
end
end
class Contact
uservar :first_name, "First Name"
uservar :last_name, "Last Name"
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
end
class Address
uservar :street, "Street"
uservar :city, "City"
uservar :country, "Country"
uservar :postal_code, "Postal Code"
def initialize(street, city, country, postal_code)
@street = street
@city = city
@country = country
@postal_code = postal_code
end
end
def dump_objects(objects)
objects.each do |object|
for k, v in object.type.uservars
print v, ": ", object.send(k), "\n"
end
print "\n"
end
end
dump_objects([Contact.new("Joe", "Schmo"), Address.new("1212 Penny Lane",
"London", "UK", "4A3B2A")])