From: Intransition Date: 2012-06-25T23:59:13+09:00 Subject: Re: Enumerable#unassociate ------=_Part_1821_8758829.1340636349942 Content-Type: multipart/alternative; boundary="----=_Part_1822_6348776.1340636349942" ------=_Part_1822_6348776.1340636349942 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit 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} ------=_Part_1822_6348776.1340636349942 Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable 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 anothe= r 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
 = #   #=3D> {:a=3D>1, :b=3D>2}
  #
&n= bsp; #   [:a, 1, :b, 2, :a, 3].h{ |v0,v1| v0.to_i + v1 }
&nb= sp; #   #=3D> {:a=3D>4, :b=3D>2}
  #
  def h(init=3D{})
    h =3D init

<= /div>
    if block_given?
      each= _slice(2) do |k,v|
        h[k] =3D yield h[k= ], v
      end
    else
<= div>      each_slice(2){ |k,v| h[k] =3D 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 (l= ike whats returned by Hash#to_a).

  [[:a= ,1], [:b,2], [:a,3]].unassociate.h{ |v0, v1| v0 << v1 }
&nb= sp; #=3D> {:a=3D>[1,3], :b=3D>2}


=
------=_Part_1822_6348776.1340636349942-- ------=_Part_1821_8758829.1340636349942--