From: Robert Klemme Date: 2007-07-13T03:25:04+09:00 Subject: Re: Returning part of a hash On 12.07.2007 19:52, barjunk wrote: > On Jul 11, 11:57 pm, "Robert Klemme" > wrote: >> 2007/7/11, barjunk : >> >> >> >>> I have hash that has about 20 keys. I'd like to create a new variable >>> with just three of those keys. Example: >>> hash = { "key1" => "value1", >>> "key2" => "value2", >>> ... >>> "key20" => "value20" } >>> And a function like: >>> newhash = hash.slice("key2","key5","key7") >>> Which creates: >>> newhash = { "key2" => "value1", >>> "key5" => "value5", >>> "key7" => "value7" } >>> hash.select {|key, value| key == "key1" } >>> I could do the above multiple times, but this returns an array not the >>> hash pair. >> irb(main):001:0> h={} >> => {} >> irb(main):002:0> 20.times {|i| h["key#{i}"]="val#{i}"} >> => 20 >> >> irb(main):008:0> h2 = Hash[*h.select {|k,v| %w{key1 key5 >> key8}.include? k}.flatten] >> => {"key1"=>"val1", "key5"=>"val5", "key8"=>"val8"} >> >> irb(main):013:0> h.dup.delete_if {|k,v| not %w{key1 key5 key8}.include? k} >> => {"key1"=>"val1", "key5"=>"val5", "key8"=>"val8"} >> >> Kind regards >> >> robert > > WOW! > > Thanks for all the options...I didn't understand the O(n^2) > conversation other than that there is a possibility for the time it > takes to get the pieces would get bigger as the array got bigger. Not sure what you mean by this. The effort for the solutions I proposed above is O(n*m) because of the linear search in the key select array. This is typically not an issue if the array is small. If it can be large then it's worthwhile to use a Set which has O(1) lookup (hash internally) and you get O(n) (n = size of Hash). Kind regards robert