0

I have the following code:

sum = array_of_hashes.select{ |key| (date_range).include? Date.parse(key[:created])}.map { |h| h[:amount] }.sum 
size = array_of_hashes.select{ |key| (date_range).include? Date.parse(key[:created])}.size
total = sum / size

sum selects all hashes with a date that is inside a date range and the adds up all the values of the :amount key.

size counts the number of hashes that are in the date range.

total divides the sum by the size.

How can I combine those so it's not 3 separate items?

0

2 Answers 2

3

I think it's as simple as:

selected = array_of_hashes.select { ... }
avarage = selected.map { ... }.sum / selected.size

Note: using include? with ranges of dates is pretty inefficient since it needs to traverse the whole dates range, I suggest to use cover? instead.

Sign up to request clarification or add additional context in comments.

7 Comments

Do you know of a way to do that in one line (even if it sacrifices a little bit of readability)?
Why do you want it on one line?
Asking if it's possible. I you can't do it, no worries. Curious if it can be done, though.
@sawa Nothing to be sorry about! :-) cover? and include? behaves almost the same when endpoints are Numerics or Strings of size 1, in any other case include? calls Enumerable#include?. In this answer you can find more information.
@sawa Yes, rb_call_super in C is, roughly, super in Ruby.
|
0

There is really no nice way of doing this more compact. One alternative could be the following:

average = (selected = array_of_hashes.select { ... }.map { ... }).sum/selected.size.to_f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.