|
|
|
|
|
|
|
Saturday, 19 June 2010 17:30 |
Source: instance_variable_get (Object) [apidock.com]
Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name.
class Fred
def initialize(p1, p2)
@a, @b = p1, p2
end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a) #=> "cat"
fred.instance_variable_get("@b") #=> 99
*update: 19-Jun-2010 @ 7:40pm*
Here's another example:
class Fred
def initialize(p1, p2)
@a, @b = p1, p2
end
def list_instance_variables
vars = self.instance_variables
vars.map{|x| "%s: %s" % [x,self.instance_variable_get(x)]}
end
end
fred = Fred.new('cat', 99)
fred.list_instance_variables
#=> ["@a: cat", "@b: 99"]
 Read more: |
|
|
|
|
|
|
|