Tintin81
Tintin81

Reputation: 10225

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?

Upvotes: 0

Views: 88

Answers (2)

Mpron
Mpron

Reputation: 132

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)

Upvotes: 0

okliv
okliv

Reputation: 3959

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

Upvotes: 5

Related Questions