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
Post a Comment