加入今天

Exercising during lockdown: A look at Ruby’s array each_cons and each_slice methods

Mesomorphic have produced a series of guides on home working, we’re reproduced in full here with permission, 但是我强烈建议你 访问他们的网站 for the most up to date information

Charlotte hasn’t been able to get to the gym recently, as she’s stuck at home due to the coronavirus lockdown. She’s having to get by with doing a lot of push-ups, and has been keeping a careful record of how many push-ups she manages to do each day. Each day’s total has been added to a Ruby array:

daily_push_up_totals = [10, 15, 25, 27, 30, 50, 55, 55, 60, 62, 62, 65, 65, 66]

RubyCopy

Charlotte would like to know two things: the total number of push-ups she’s done each week, and her greatest improvement from one day to the next.

To calculate the total of number of push-up Charlotte has done each week, one approach would be to use each_slice. This Array method divides the array into sections (or slices) and passes each section to the block. The number of values in each section is passed in as a parameter. 举个例子:

daily_push_up_totals.each_slice (7) { |week_totals| print weekly_totals }

RubyCopy

会导致:

    [10, 15, 25, 27, 30, 50, 55][55, 60, 62, 62, 65, 65, 66]

ConsoleCopy

We’ve managed to divide up the array into slices of seven values each, so all we need to do obtain the weekly totals is to add up each slice using 总和:

daily_push_up_totals.each_slice (7) { |week_totals| puts "Weekly total: #{week_totals.总和}}

RubyCopy

导致:

    每周总数:212
    每周总数:445

ConsoleCopy

We can make the output more useful by using with_index:

daily_push_up_totals.each_slice (7).with_index(1) { |week_totals, week_number| puts "Total for week #{week_number}: #{week_totals.总和}}

RubyCopy

这将给我们:

    Total for week 1: 212
    Total for week 2: 445

ConsoleCopy

So how can we figure out Charlotte’s greatest day-on-day improvement? 让我们试着使用 each_cons. This Array method supplies the given block with n consecutive elements, starting from each element in turn. 困惑? An example should make things clearer:

daily_push_up_totals.each_cons (2){ |values| print values }

RubyCopy

将返回:

 [10, 15][15, 25][25, 27][27, 30]...

ConsoleCopy

等等.......

鉴于这种, calculating the greatest day-on-day improvement is a case of finding the differences between each of these pairs of daily totals, and finding the 马克斯imum:

daily_push_up_totals.each_cons (2).map{ |day1, day2| day2 - day1 }.马克斯

RubyCopy

返回:

 20

ConsoleCopy

We’re done – Charlotte will now be able to keep track of her progress no matter how long the lockdown lasts.

多亏了 亚当·L. 沃森 for spotting an error in a previous version of this post.

I’d love to hear your thoughts on each_sliceeach_cons, the uses you’ve found for them, and indeed, exercising during lockdown. Why not leave a comment below?

滚动到顶部
X