Best way to add a method to the Array class

Hey guys, whats the best way to add a method to the array class so that
it will act on an array? Can you give an example?

On 10/19/06, Eric G. [email protected] wrote:

Hey guys, whats the best way to add a method to the array class so that
it will act on an array? Can you give an example?

Ruby classes are open, so you can simply do:

class Array
def sum
inject(0) { |sum,v| sum+=v }
end
end

You can also redefine existing methods, but you’ll have to be very
careful with that. alias is your friend.

Cheers,
Max

where would that code snippet go?

In the application controller?

Max M. wrote:

On 10/19/06, Eric G. [email protected] wrote:

Hey guys, whats the best way to add a method to the array class so that
it will act on an array? Can you give an example?

Ruby classes are open, so you can simply do:

class Array
def sum
inject(0) { |sum,v| sum+=v }
end
end

You can also redefine existing methods, but you’ll have to be very
careful with that. alias is your friend.

Cheers,
Max

On 10/19/06, Eric G. [email protected] wrote:

where would that code snippet go?

In the application controller?

No. Create a new file under lib, for example array_extensions.rb and
you should be fine.

Max

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs