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

S

Simon Strandgaard

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.php?sid=333

Any thoughts ?
 
F

Florian Gross

Moin!

Simon said:
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
 
S

Simon Strandgaard

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

Harry Ohlsen

Florian said:
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.
 
D

Dan Doel

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top