siekfried
siekfried

Reputation: 2964

Create a nested hash to organize objects

I have a Payment model which belongs to Currency and PaymentMode. Currency and PaymentMode have many Payments.

On the index page of my payments, I have a list of every payments, and I would like to be able to sort them by currency and by payment mode.

Let's say for example that I have three currencies (CHF, Dollars, Euros) and two payments mode (Cash and BlueCard).

What I want to obtain is something like this :

{
  CHF => {
           Cash => [array of corresponding payments], 
           BlueCard => [...]}, 
  Dollars => {
               Cash => [...], 
               BlueCard => [...]}, 
  Euros => {
             Cash => [...], 
             BlueCard => [...]}
}

What is the best way to achieve this?

Thanks in advance!

Upvotes: 3

Views: 1782

Answers (1)

Arkan
Arkan

Reputation: 6236

What about something like this ?

def get_hash_from_payments(payments)
  result_hash = {}
  payments.each do |payment|
    result_hash[payment.currency.symbol] ||= {}
    result_hash[payment.currency.symbol][payment.payment_mode.name] ||= []
    result_hash[payment.currency.symbol][payment.payment_mode.name] << payment #Or whatever info you need from payment.
  end
  result_hash
end

Upvotes: 4

Related Questions