class Friend attr_accessor :name, :age, :phone def initialize(name, age, phone) @name, @age, @phone = name, age, phone end end f1 = Friend.new("John", 30, "555-1212") f1.instance f1.instance.update({:name=>'Jerry'}) f1.instance
# File lib/core/facets/instance.rb, line 34 def initialize(delegate) @delegate = delegate end
# File lib/core/facets/instance.rb, line 92 def <<(pair) name, value = *pair name = atize(name) @delegate.instance_variable_set(name, value) end
# File lib/core/facets/instance.rb, line 80 def [](name) name = atize(name) @delegate.instance_variable_get(name) end
# File lib/core/facets/instance.rb, line 86 def []=(name, value) name = atize(name) @delegate.instance_variable_set(name,value) end
A hold-over from the the old instance_assign method.
# File lib/core/facets/instance.rb, line 44 def each @delegate.instance_variables.each do |name| yield(name[1..-1].to_sym, @delegate.instance_variable_get(name)) end end
Instance evaluation.
# File lib/core/facets/instance.rb, line 146 def eval(*a,&b) @delegate.instance_eval(*a,&b) end
# File lib/core/facets/instance.rb, line 39 def instance_delegate @delegate end
Instance vairable names as symbols.
# File lib/core/facets/instance.rb, line 125 def keys @delegate.instance_variables.collect do |name| name[1..-1].to_sym end end
Instance variable names as strings.
# File lib/core/facets/instance.rb, line 132 def names @delegate.instance_variables.collect do |name| name[1..-1] end end
Return instance variables with values as a hash.
class X def initialize(a,b) @a, @b = a, b end end x = X.new(1,2) x.instance.to_h #=> { :a=>1, :b=>2 }
# File lib/core/facets/instance.rb, line 62 def to_h(at=false) h = {} if at @delegate.instance_variables.each do |name| h[name] = @delegate.instance_variable_get(name) end else each do |key, value| h[key] = value end end h end
Set instance variables given a hash
.
instance.update('@a'=>1, '@b'=>2) @a #=> 1 @b #=> 2
Also, +@+ sign is not neccessary.
instance.update(:a=>1, :b=>2) @a #=> 1 @b #=> 2
# File lib/core/facets/instance.rb, line 110 def update(hash) hash.each do |pair| self << pair end end
Instance variable values.
# File lib/core/facets/instance.rb, line 139 def values @delegate.instance_variables.collect do |name| @delegate.instance_variable_get(name) end end
Same as instance_variables.
# File lib/core/facets/instance.rb, line 120 def variables @delegate.instance_variables end