Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 687
siekfried Avatar asked May 06 '26 15:05

siekfried


1 Answers

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
like image 51
Arkan Avatar answered May 08 '26 06:05

Arkan