Issue #4910 has been updated by Benoit Daloze.


Hello,

Robert Klemme wrote:
> I suggest to add these two to class Class:
> 
> class Class
>   alias call new
> 
>   def to_proc(*args)
>     lambda {|*a| new(*args)}
>   end
> end

Did you want to mean:
def to_proc
  lambda { |*args| new(*args) } # or maybe lambda { |args| new(*args) }
end
?

#to_proc is called with no arguments (Symbol.instance_method(:to_proc).arity # => 0).

> 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).

I don't really see the advantage of defining #call, you could use #new instead at line 16.
If you want more flexibility, I believe it is fine to use a block.

But I like Class#to_proc, and it is indeed some kind of factory helper:

  Pos = Struct.new :x,:y
  [[1,2],[3,4]].map(&Pos) # => [#<struct Pos x=1, y=2>, #<struct Pos x=3, y=4>]
  # instead of
  [[1,2],[3,4]].map { |x,y| Pos.new(x,y) }

  # note neither #to_proc defined as "lambda { |*args| new(*args) }" nor map(&Pos.method(:new)) would work:
  # ([#<struct Pos x=[1, 2], y=nil>,...])

The obvious limitation being the lack of flexibility for common arguments (e.g.: y always the same). You would then have to use an explicit block.

I do not know if it is worth to add it for this specific case, but it can be nice.

I am also unsure if we need factories in Ruby (certainly not like in statically typed languages).
----------------------------------------
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