Project

General

Profile

Feature #6669

Updated by nobu (Nobuyoshi Nakada) over 9 years ago

=begin 
 Given a hash `h`, `h.map` h, h.map returns an array(alist), but sometimes I hope it returned a hash. 

 Example: 

 ~~~ruby 
 

   class Hash 
   
     def apply(&block) 
     
       self.inject({}) do |h, (k, v)| 
       
         new_k, new_v = *block.call(k, v) 
       
         h[new_k] = new_v 
         h 
       h end 
     end 
   end 
 end 

 
  
   score = { 
   
     taro: [1,3,2], 
    
     jiro: [3,5,8,4], 
    
     saburo: [2,9] 
 
   } 
 
   max_score = score.apply{|k,v| [k, v.max]} 
 
   #=> {taro: 3, jiro: 8, saburo: 9} 
 
   p max_score[:taro] 
 
   #=> 3 
 ~~~ 

 I'm not thinking "`apply`" "apply" is a perfect name for this. Maybe "`hash_map`" "hash_map" is better 
 (we already have "`flat_map`"). "flat_map"). 
 =end 

Back