简体   繁体   中英

How to loop through arrays of different length in Ruby?

Let's say i have two relation arrays of a user's daily buy and sell.

how do i iterate through both of them using .each and still let the the longer array run independently once the shorter one is exhaused. Below i want to find the ratio of someone's daily buys and sells. But can't get the ratio because it's always 1 as i'm iterating through the longer array once for each item of the shorter array.

users = User.all
ratios = Hash.new

users.each do |user|

  if user.buys.count > 0 && user.sells.count > 0

    ratios[user.name] = Hash.new
    buy_array = []
    sell_array = []
    date = ""

    daily_buy = user.buys.group_by(&:created_at)
    daily_sell = user.sells.group_by(&:created_at)

    daily_buy.each do |buy|
      daily_sell.each do |sell|
        if buy[0].to_date == sell[0].to_date
          date = buy[0].to_date
          buy_array << buy[1]
          sell_array << sell[1]
        end
      end
    end
    ratio_hash[user.name][date] = (buy_array.length.round(2)/sell_array.length)
  end
end

Thanks!

You could concat both arrays and get rid of duplicated elements by doing:

(a_array + b_array).uniq.each do |num|
  # code goes here
end

Uniq method API

daily_buy = user.buys.group_by(&:created_at)
 daily_sell = user.sells.group_by(&:created_at

  buys_and_sells = daily_buy + daily_sell

  totals = buys_and_sells.inject({}) do |hsh, transaction|
    hsh['buys'] ||= 0;
    hsh['sells']  ||= 0;
    hsh['buys'] += 1 if transaction.is_a?(Buy)
    hsh['sells'] += 1 if transaction.is_a?(Sell)
    hsh
  end

  hsh['buys']/hsh['sells']

I think the above might do it...rather than collecting each thing in to separate arrays, concat them together, then run through each item in the combined array, increasing the count in the appropriate key of the hash returned by the inject.

In this case you can't loop them with each use for loop this code will give you a hint

ar = [1,2,3,4,5]
br = [1,2,3]

array_l = (ar.length > br.length) ? ar.length : br.length

for i in 0..array_l
    if ar[i] and br[i]
        puts ar[i].to_s + " " + br[i].to_s
    elsif ar[i]
      puts ar[i].to_s
    elsif br[i]
      puts br[i].to_s
    end
end

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