Explain what is happening with ternary operator in Ruby method -


i have method working purposes, thing don't know going on , use explaination in laymans terms. last evaluated line:

hash.map{ |k,v| v==max[1] ? k : nil }.compact.sort_by(&:length).first 

this code:

 def self.largest_hash_key(hash)     max = hash.max_by{ |k,v| v }     7 = hash.max_by{ |k,v| k.length }.first     if seven.length == 7      7     else      hash.map{ |k,v| v==max[1] ? k : nil }.compact.sort_by(&:length).first     end   end 

map returns projection based on value(s) passed in. in case returning array made of - each key/value pair - hash key or nil, depending on whether value matches max[1].

[1, 2, 3].map{|a| a.odd? ? : nil} => [1, nil, 3] 

in case, hash converted keys values match max[1] (nils stripped out compact), sorted length, , first (smallest length) returned.

this algorithm can use quite bit of improvement, that's how line in question works.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -