[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

[RCR] #inject, #partition expand array if arity > 2

Simon Strandgaard

10/29/2003 7:28:00 PM

It would be awesome, if #inject could do splitting when arity > 2.
For instance converting an array of pairs into a hash (arity==3):

x=[["name", "john"], ["age", 20]]
p x.inject({}){|h,k,v|h[k]=v;h}
#=> {"name"=>"john", "age"=>20}

Also #partition cannot deal with arity > 2..
All other iterator methods seems to deal ok with arity>2.
Have I forgotten any iterator methods ?


I have submitted the RCR here:
http://www.rubygarden.org/article.p...

Any thoughts ?

--
Simon Strandgaard
4 Answers

Florian Gross

10/29/2003 8:00:00 PM

0

Moin!

Simon Strandgaard wrote:

> It would be awesome, if #inject could do splitting when arity > 2.
> For instance converting an array of pairs into a hash (arity==3):

> x=[["name", "john"], ["age", 20]]
> p x.inject({}){|h,k,v|h[k]=v;h}
> #=> {"name"=>"john", "age"=>20}

This is already possible with a built-in ruby feature:

x=[["name", "john"], ["age", 20]]
x.inject({}) { |h, (k,v)| h[k]=v; h } # => {"name"=>"john", "age"=>20}

Regards,
Florian Gross



Simon Strandgaard

10/29/2003 9:51:00 PM

0

On Thu, 30 Oct 2003 04:59:57 +0900, Florian Gross wrote:
[snip]
> x=[["name", "john"], ["age", 20]]
> x.inject({}) { |h, (k,v)| h[k]=v; h } # => {"name"=>"john", "age"=>20}
^^^^^
Thats nice.. I wasn't aware of this feature.
I will start from today using parantesis this way.

--
Simon Strandgaard

Harry Ohlsen

10/29/2003 9:56:00 PM

0

Florian Gross wrote:

> Moin!
> This is already possible with a built-in ruby feature:
>
> x=[["name", "john"], ["age", 20]]
> x.inject({}) { |h, (k,v)| h[k]=v; h } # => {"name"=>"john", "age"=>20}

I've not seen that syntax/semantics before. Is the |(k,v)| syntax documented somewhere?

I'm guessing it's not in Pickaxe, since inject didn't appear until later ... or is this kind of syntax generally available when iterating over hashes (or anything with key/value pairs)?

It seems incredibly useful!

Cheers,

Harry O.



Dan Doel

10/29/2003 10:17:00 PM

0

I believe it's just assignment semantics.

Block parameters are set in the same way that an assignment statement is
evaluated, so essentially, it's the same as something like:

x = [["name", "john"], ["age", 20]]

h, (k,v) = {}, x[0]

which does:
h = {}
(k,v) = ["name", "john"] # (k = "name", v = "john")

When assignments involve commas, they're implicitly converted to arrays, so
the above is the same as:

[h, [k, v]] = [{}, x[0]]

which explains why things happen the way they do.

Cheers,

- Dan