i thought i’m a Ruby giant when i wrote this oneliner:
# having this hash
hash = { 'Portugal' => 1, 'France' => 2, 'USA' => 3 }
# country_id comes from input
country_name = (hash.select { |k,v| v == country_id.to_i }.first || []).first
it does correctly extract the country name and does Not fail if country not found.
i’m totally pleased with it.
however my tutor says it can/should be optimized in terms of readability, length and performance!
what can be clearer/faster than this?
please advise
well, seems your tutor is right 🙂
you can do like this:
or, as suggested by @littlecegian
or, as suggested by @steenslag
Full example:
will print:
see it running here