aaron
aaron

Reputation: 2056

Possible to extend methods of Array in ruby?

I have an array of instances of e.g. class Result, I want to join names of results rather than results with a ',' like below:

@results=[result1, result2...]
results.join(", ") do |r|
   r.name
end

results.join method should be an extensino methods of Array, I want it available to all arrays in my program.

Possible?

Upvotes: 1

Views: 561

Answers (1)

David Grayson
David Grayson

Reputation: 87386

Yes, this is possible.

class Array
  def join_names
    collect(&:name).join(", ")
  end
end

But this makes it more likely that you code will have namespace collisions with other libraries that add methods to the Array class.

Upvotes: 3

Related Questions