ruby - remove element from hash based on pattern -


i have hash looks this:

{ "cell_number" => 1234567,  "lead source" => [ "referrel", "web", "ad" ], "lead source_selected" => "web" } 

now if there pattern key contains "x_selected", want return entire hash, except x key. in case want return "lead source":

{ "cell_number" : 1234567,  "lead source_selected" : "web" } 

my attempt seems work:

 h = { "cell_number" => 1234567,  "lead source" => [ "referrel", "web", "ad" ], "lead source_selected" => "web" }  h.collect |k,v|   if k =~ /(.+)_selected$/     h.delete( $1 )   end  end  => [nil, nil, ["referrel", "web", "ad"]]   > h  => {"cell_number"=>1234567, "lead source_selected"=>"web"}  

but there more ruby way this?

a straightforward solution:

h = { "cell_number" => 1234567,       "lead source" => [ "referrel", "web", "ad" ],       "lead source_selected" => "web" }  bad_keys = h.each_with_object([]) |(k,_),a|   prefix = k[/(.+)(?=_selected$)/]   << prefix if prefix end   #=> ["lead source"] h.reject { |k,_| bad_keys.include?(k) }   #=> {"cell_number"=>1234567, "lead source_selected"=>"web"}  

note uses hash#reject (not enumerable#reject). (?=_selected$) in regex positive lookahead. h not mutated.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -