1

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?

4
  • 1
    #join is already an array method... what are you asking for exactly? Commented Nov 14, 2011 at 4:08
  • 1
    Why should it be available to all arrays if it only works on arrays of objects that respond to "name"? Besides, you can already collect or map and get the same effect without polluting a general-purpose class with message-specific functionality. Yes, it's possible. Commented Nov 14, 2011 at 4:09
  • Yes, join is already a method of array, what I want is the join which can take a block. like def join(delim) { array.map {|x| yield(x) }.join(delim)} Commented Nov 14, 2011 at 4:14
  • The code you posted doesn't even work because join does not take a block. You need to use collect and then join. Commented Nov 14, 2011 at 4:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. What I want should be like this, which means I want to override/overload? the existing join function of Array, possible and any problem? class Array def join(delim) if block_given? self.map { |item| yield(item) }.join(delim) else self.join(delim) end end end
Overriding the built-in function isn't a good idea. Extend Array and define a new method, like join_names, as in the answer here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.