a = Array(11…20)
class Foo
attr_reader :a
a = 123
def initialize(i)
@a = Array(1…10)
end
def change()
puts
puts “Inside of change!!!”
a[2] = 111111 # intentionally not using @a
end
def print_it
puts
p “Printing Object”
p @a
end
end
foo = Foo.new(3)
foo.print_it
foo.change
foo.print_it
foo.a[3] = 222222
foo.print_it
puts
p “Global var”
p a
if you like, you can write down the output of the above code, like in a
quiz…
i will post the answer at the end of the post.
but is this how to interpret the program?
-
you don’t need to use @a[2] = 111111 in change() but can use a[2] =
111111 because a is now the method name… it returns an array, and
therefore the instance method can modify the content of the array. -
foo.a[3] = 222222 can actually modify the array like (1) above… so,
even though you are just using reader method, other routines can
actually modify the content of an object. the moral of the story is to
not return an array? because an array class is not protecting its
content – any code can change its content. -
what is the “a = 123” near the line “class Foo” near the top of the
program? What is it, it is not local, not class variable, not instance
variable, not global… so what is it? the program is not complaining
the existence of it.
NOW HERE IS THE OUTPUT OF THE PROGRAM ABOVE.
MAKE SURE YOU DON’T WANT TO TRY AND WRITE DOWN THE ANSWER FIRST
BEFORE LOOKING AT THE ANSWER:
C:\rails\depot>ruby test_class02.rb
“Printing Object”
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Inside of change!!!
“Printing Object”
[1, 2, 111111, 4, 5, 6, 7, 8, 9, 10]
“Printing Object”
[1, 2, 111111, 222222, 5, 6, 7, 8, 9, 10]
“Global var”
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]