On Monday, June 25, 2012 2:38:48 AM UTC-4, Robert Klemme wrote:
> What's the use case for this?
>
In my case it's supplemental to another method I am working on. I have no
name for it yet, so call it #h.
# Convert an Enumerable object to a Hash.
#
# [:a, 1, :b, 2].h
# #=> {:a=>1, :b=>2}
#
# [:a, 1, :b, 2, :a, 3].h{ |v0,v1| v0.to_i + v1 }
# #=> {:a=>4, :b=>2}
#
def h(init={})
h = init
if block_given?
each_slice(2) do |k,v|
h[k] = yield h[k], v
end
else
each_slice(2){ |k,v| h[k] = v }
end
h
end
The #unassociate method qould be of use as a preparation for using h, since
this doesn't work with associative arrays (like whats returned by
Hash#to_a).
[[:a,1], [:b,2], [:a,3]].unassociate.h{ |v0, v1| v0 << v1 }
#=> {:a=>[1,3], :b=>2}
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en