Create a nested hash to organize objects

I have a model Payment

that belongs to Currency

and PaymentMode

. Currency

and PaymentMode

have a lot Payments

.

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

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

What I want to get 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!

+3


source to share


1 answer


How about 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

      

+4


source







All Articles