Robert Klemme
10/30/2003 8:41:00 AM
"Simon Strandgaard" <qj5nd7l02@sneakemail.com> schrieb im Newsbeitrag
news:pan.2003.10.29.18.40.10.757877@sneakemail.com...
> On Wed, 29 Oct 2003 19:07:38 +0100, Simon Strandgaard wrote:
>
> > On Wed, 29 Oct 2003 17:14:40 +0100, Robert Klemme wrote:
> > [snip]
> >> module Enumerable
> >> def to_hash
> >> h={}
> >> each do |k,v|
> >> h[k]=v
> >> end
> >> h
> >> end
> >> end
> >>
> >> Then:
> >>
> >> irb(main):033:0> ["name","age"].zip(["john",20]).to_hash
> >> => {"name"=>"john", "age"=>20}
> >>
> >
> > Why are #inject not splitting the pair into k and v ?
> >
> > irb(main):011:0> x=[["name", "john"], ["age", 20]]
> > => [["name", "john"], ["age", 20]]
> > irb(main):012:0> x.inject({}){|h,k,v|h[k]=v;h}
> > => {["name", "john"]=>nil, ["age", 20]=>nil}
> > irb(main):013:0>
> >
> > Should'nt #inject do that ?
>
>
> I whish something like this:
>
> module Enumerable
> def foldr(n, &block)
> if block.arity == 2
> each{|v|n=block.call(n,v)}
> else
> each{|v|n=block.call(n,*v)}
> end
> n
> end
> end
>
> x=[["name", "john"], ["age", 20]]
> p x.foldr({}){|h,k,v|h[k]=v;h}
> #=> {"name"=>"john", "age"=>20}
This is not nice:
irb(main):015:0> {1=>2,3=>4}.foldr({}){|a,b| p [a,b]}
(irb):5: warning: multiple values for a block parameter (2 for 1)
from (irb):5
[{}, [1, 2]]
(irb):5: warning: multiple values for a block parameter (2 for 1)
from (irb):5
[nil, [3, 4]]
=> nil
irb(main):016:0>
> Perhaps I should submit a RCR for changing #inject into the above #foldr
?
I would not do that. It does not feel right. The fact, that the constant
2 appears in the implementation smells like too much specialization IMHO.
Better sleep one more night about this... :-)
Kind regards
robert