2 # Available in 1.8.6 and later.
3 unless respond_to
?(:instance_variable_defined?)
4 def instance_variable_defined
?(variable
)
5 instance_variables
.include?(variable
.to_s
)
9 # Returns a hash that maps instance variable names without "@" to their
10 # corresponding values. Keys are strings both in Ruby 1.8 and 1.9.
13 # def initialize(x, y)
18 # C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
19 def instance_values
#:nodoc:
20 instance_variables
.inject({}) do |values
, name
|
21 values
[name
.to_s
[1..-1]] = instance_variable_get(name
)
26 # Returns an array of instance variable names including "@". They are strings
27 # both in Ruby 1.8 and 1.9.
30 # def initialize(x, y)
35 # C.new(0, 1).instance_variable_names # => ["@y", "@x"]
36 if RUBY_VERSION >= '1.9'
37 def instance_variable_names
38 instance_variables
.map
{ |var
| var
.to_s
}
41 alias_method
:instance_variable_names, :instance_variables
44 # Copies the instance variables of +object+ into +self+.
46 # Instance variable names in the +exclude+ array are ignored. If +object+
47 # responds to <tt>protected_instance_variables</tt> the ones returned are
48 # also ignored. For example, Rails controllers implement that method.
50 # In both cases strings and symbols are understood, and they have to include
54 # def initialize(x, y, z)
55 # @x, @y, @z = x, y, z
58 # def protected_instance_variables
66 # a.copy_instance_variables_from(b, [:@y])
67 # # a is now: @x = 3, @y = 1, @z = 2
68 def copy_instance_variables_from(object
, exclude
= []) #:nodoc:
69 exclude
+= object
.protected_instance_variables
if object
.respond_to
? :protected_instance_variables
71 vars
= object
.instance_variables
.map(&:to_s) - exclude
.map(&:to_s)
72 vars
.each
{ |name
| instance_variable_set(name
, object
.instance_variable_get(name
)) }