简体   繁体   中英

What is the most efficient way to retrieve an element from a multidimensional array in Ruby?

Let's assume I have a multidimensional array like this:

CURRENCIES = [
  [ "EUR", "€" ],
  [ "USD", "$" ],
  [ "GBP", "£" ]
]

What is the most efficient way in Ruby to retrieve a currency symbol by providing a currency code?

convert it to hash:

currencies_hash = Hash[CURRENCIES]

and then get what you need:

currencies_hash["EUR"] #=>"€"

i don't know if it is most efficient (for memory usage or CPU Time or ?..) but Ruby-style elegant enough =)

and if you can define CURRENCIES as a hash then you do not need an array

Not sure if you need to convert those nested arrays into a hash programmatically, but if you do, here's how you would do that.

def hash(a)
   h = {}
   a.each { |x| h[x[0]] = x[1] }
   h
end

CURRENCIES = hash(your_array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM