A quick question: is it possible to monkey patch the Array [] method in
ruby?
I tried:
class Array
def []=(elem)
raise ‘Yesss… It works!’
end
end
But that didn’t work. I tried patching the Kernel module but that didn’t
have any effect either. Is the [] hidden else somewhere? Or do I have to
use rubinius for that?
A quick question: is it possible to monkey patch the Array [] method in
ruby?
I tried:
class Array
def []=(elem)
raise ‘Yesss… It works!’
end
end
But that didn’t work. I tried patching the Kernel module but that didn’t
have any effect either. Is the [] hidden else somewhere? Or do I have to
use rubinius for that?
Thanks!
Leon
You redefined the []= method, not the [] method.
class Array
def # just get rid of the “=”
raise ‘Yesss… It works!’
end
end
I know it’s bad behaviour But I’m just fiddling with ruby.
class Array
def # just get rid of the “=”
raise ‘Yesss… It works!’
end
end
a = [‘one’, ‘two’, ‘three’]
p a
Didn’t work also. It just prints: [“one”, “two”, “three”]
try
p a[0]
[] is just a method. You chanced it. To verify if your change works, you
'll have to use the [] method. If this is not what you want, what
outcome did you expect?