in Ruby, how to extract a key from the Hash having the value -


I thought I'm Ruby huge when I wrote this:

  # this hash Hash = {'Portugal' = & gt; 1, 'France' = & gt; 2, 'USA' = & gt; 3} # country_id input comes from country_name =. (Hash .select {| k, v | v == country_id.to_i} .first || []). First   

This is to be removed in the right way, the country's name and if the country is not found then it does not fail.

I am completely happy with it.

Although my tutor says that according to readability it can be customized, length and performance!

What can be more clear / sharp than this?

Please give advice

OK, it seems that your tutor is right :)

You can do this:

  hash.invert [country_id.to_i] # will work on all editions   

Or, as suggested by @littlecegian

  hash (country_id.to_i) will work on # 1.9   

or, as is done by @steenslag Recommended

  hash.index (country_id.to_i) will work on # 1.8 and 1.9, with a warning on 1.9  with / past> 

full example:

  hash = {'Portugal' = & gt; 1, 'France' = & gt; 2, 'USA' = & gt; 3}% w [2 3 1 Bla]. Country_id | # All versions country_name = hash.invert [country_id.to_i] # 1.9 only country_name = hash.key (country_id.to_i) # 1.8 and 1.9, 1.9 country_name with a warning = hash.index (country_id.to_i) printf "country_id =% S, country_name =% s \ n ", country_id, country_name end   

will print:

  country_id = 2, country_name = France country_id = 3 , Country_name = USA country_ id = 1, country_name = Portugal country_ id = blah, country_name =   

see it running

Comments

Popular posts from this blog

Python SQLAlchemy:AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'schema' -

java - How not to audit a join table and related entities using Hibernate Envers? -

mongodb - CakePHP paginator ignoring order, but only for certain values -