Issue #4910 has been updated by Robert Klemme.


Charles Nutter wrote:
> I'm not sure I agree with adding to_proc to Class instances, since it seems questionable that #new is what you'd always want to be called.

Hmm, but what else?  I think it is a reasonable default.

> Dodging that debate for now, there is another way to get the result you seek:
> 
> class Foo
>   def initialize(i)
>     @i = i
>   end
> end
> 
> (1..50).map(&Foo.method(:new))
> 
> This is both more explicit and less magic. If there were syntax added to get method objects (without calling #method) it would be even cleaner.

That's true.  Though in absence of that syntax I prefer (1..50).map {|i| Foo.new i} over your solution as it is equally explicit and even less magic - could even be shorter to type. :-)  Actually only (1..50).map(&Foo) would be an alternative I would consider.

Cheers
----------------------------------------
Feature #4910: Classes as factories
http://redmine.ruby-lang.org/issues/4910

Author: Robert Klemme
Status: Open
Priority: Normal
Assignee: 
Category: 
Target version: 


I suggest to add these two to class Class:

class Class
  alias call new

  def to_proc(*args)
    lambda {|*a| new(*args)}
  end
end

Then we can use class instances where blocks are needed and can easily use them as factory instances using the general contract of #call (see example attached).


-- 
http://redmine.ruby-lang.org