Skip to content

Instantly share code, notes, and snippets.

@MrBean83
Last active December 20, 2015 07:19
Show Gist options
  • Select an option

  • Save MrBean83/6092939 to your computer and use it in GitHub Desktop.

Select an option

Save MrBean83/6092939 to your computer and use it in GitHub Desktop.
"Count the numbers in an array between a given range"
def count_between(array, lower_bound, upper_bound)
count = 0
array.each do |num|
if ((num >= lower_bound) && (num <= upper_bound))
count += 1
end
end
return count
end
@zdavy
Copy link

zdavy commented Jul 27, 2013

Oh wow, you're really close. Instead of trying to get a count on the array, start a counter and after you array.each do I add += 1 with a conditional statement that it's within the range.

@zdavy
Copy link

zdavy commented Jul 27, 2013

I went a different route though, I went with

array.select { |x| x <= upper_bound && x >= lower_bound }.size

@zdavy
Copy link

zdavy commented Jul 27, 2013

ohhhh, you don't need the array.compact and array.count

all you need to put is count

def count_between(array, lower_bound, upper_bound)
count = 0
array.each do |num|
if ((num >= lower_bound) && (num <= higher_bound))
count += 1
eliminate the else part of the statement, it's understood that if it doesn't fulfill the if statement it doesn't do anything
end
return count
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment