M
Marcelo Alvim
Hi,
Well, I'm new to Ruby (I've been working and playing with it for the
last 6 months only), and
I know there's probably another way in which this could work, but
somehow I feel like the
code below should work. Let's see what you guys think about it.
The idea is making a copy of a class object, changing it and then
restoring it back to what it was after playing with the new stuff I
added. It should go somewhat like this:
OldArray = Array.dup
# => OldArray
class Array
def my_method; "My Method"; end
end
# => nil
[].my_method
# => "My Method"
x = Array.new
# => []
x.my_method
# => "My Method"
### Switch back
Array = OldArray.dup
(irb):9: warning: already initialized constant Array
# => Array
x.my_method
# => "My Method"
(Ok, now why did that work? Maybe "x" is still using the modified Array class?)
[].my_method
# => "My Method"
(Same thing here, it seems)
[1, 2, 3].my_method
# => "My Method"
(Hmmmm, let's try something different)
x = Array.new
# => []
x.my_method
NoMethodError: undefined method `my_method' for []:Array
from (irb):14
from :0
(Ok, so new instances only? Is this weird at all, or is this the way
it's supposed to work?)
I'm asking these questions out of real lack of knowledge, and I REALLY
don't suppose
something should change in order to make this work. I'm just trying to
understand how
Ruby does all this stuff.
Thank you in advance,
Marcelo Alvim.
Well, I'm new to Ruby (I've been working and playing with it for the
last 6 months only), and
I know there's probably another way in which this could work, but
somehow I feel like the
code below should work. Let's see what you guys think about it.
The idea is making a copy of a class object, changing it and then
restoring it back to what it was after playing with the new stuff I
added. It should go somewhat like this:
OldArray = Array.dup
# => OldArray
class Array
def my_method; "My Method"; end
end
# => nil
[].my_method
# => "My Method"
x = Array.new
# => []
x.my_method
# => "My Method"
### Switch back
Array = OldArray.dup
(irb):9: warning: already initialized constant Array
# => Array
x.my_method
# => "My Method"
(Ok, now why did that work? Maybe "x" is still using the modified Array class?)
[].my_method
# => "My Method"
(Same thing here, it seems)
[1, 2, 3].my_method
# => "My Method"
(Hmmmm, let's try something different)
x = Array.new
# => []
x.my_method
NoMethodError: undefined method `my_method' for []:Array
from (irb):14
from :0
(Ok, so new instances only? Is this weird at all, or is this the way
it's supposed to work?)
I'm asking these questions out of real lack of knowledge, and I REALLY
don't suppose
something should change in order to make this work. I'm just trying to
understand how
Ruby does all this stuff.
Thank you in advance,
Marcelo Alvim.