From: Trans Date: 2007-07-13T12:13:07+09:00 Subject: Re: Returning part of a hash On Jul 12, 3:24 pm, Stefan Rusterholz wrote: > Trans wrote: > > def &(other) > > case other > > when Array > > k = (keys & other) > > Hash[*(k.zip(values_at(*k)).flatten)] > > else > > Hash.new[*(to_a & other.to_a).flatten] > > end > > end > > > end > > > T. > > > --- > >http://facets.rubyforge.org > > Hash[*something.flatten] will destroy any nested arrays (and if you're > so unlucky to get an even amount of elements, it won't even raise). Ah, nice catch thanks. I fixed it. But in the process, well, I just have to get this off my chest.... Arrggghh!!!! Where's flatten(x)!? I know David Black asked for that like YEARS AND YEARS ago and we still we don't have it? Come on! Please, please put it in 1.9. I even wrote the C code myself two years ago. I'll post it up on ruby-core. Okay? Okay? Okay. Sorry for the digression... In any case, I worked around: def &(other) case other when Array k = (keys & other) Hash[*(k.zip(values_at(*k)).flatten)] else r = (to_a & other.to_a).inject([]) do |a, kv| a.concat kv; a end Hash[*r] end end Better? That last version had a bug anyway --Hash.new[] should have been Hash[]. Thanks Stefan, T.