Quickie: Monkey patching Array

Hi all,

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? :slight_smile:

Thanks!

Leon

On May 29, 2008, at 3:51 PM, Leon B. wrote:

raise 'Yesss... It works!'

end
end

Try [], not []=. They’re different methods.

On May 29, 2008, at 23:51, Leon B. wrote:

Hi all,

A quick question: is it possible to monkey patch the Array [] method
in
ruby?

I tried:

class Array
def []=(elem)

You monkey patched the []= method, not the [] method. Try
def

Also: Are you sure this is necessary? I can only imagine overwriting
Array#[] can lead to bad things.

Leon B. wrote:

Hi all,

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? :slight_smile:

Thanks!

Leon

You redefined the []= method, not the [] method.
class Array
def # just get rid of the “=”
raise ‘Yesss… It works!’
end
end

groeten,

Siep

I know it’s bad behaviour :slight_smile: 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”]

Hee Siep,

Well, actually I tried to change the [] method with which you create
arrays. This one: [‘one’, ‘two’, ‘three’]

I tried looking if it exists in the ruby kernel:
http://www.ruby-doc.org/core/classes/Kernel.html

But I couldn’t find it.

Leon

Leon B. wrote:

I know it’s bad behaviour :slight_smile: 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?

regards,

Siep

On May 30, 2008, at 0:18, Leon B. wrote:

class Array
def # just get rid of the “=”
raise ‘Yesss… It works!’
end
end

a = [‘one’, ‘two’, ‘three’]

That’s an array literal, not Array#[]. No way to overload that, I’m
afraid. Try running:
a[0]

Ah, I read the post about the array literal.

Thanks for the replies! I’ll try and make it work another way .

Leon