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
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
(Dan Doel)
29 October 2003 22:17
3
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,