How can I check a range with decimal place in ruby?
I want to filter results in an array between 9.74 - 9.78 in ruby
if (9.74...9.78) == amounts
count += 1
end
This seems not to work
Do this using Range#cover
:
if (9.74...9.78).cover? amounts
count += 1
end
Example :
p (9.74...9.78).cover? 9.75 # => true
p (9.74...9.78).cover? 9.79 # => false
Update as @m_x suggested
# will give you the element in the range
array.select{ |item| (9.74..9.78).cover? item }
# will give you the element count in the array belongs to the range
array.count{ |item| (9.74..9.78).cover? item }
Just put the numbers in parentheses and ===
:
if ((9.74)...(9.78)) === amounts
count += 1
end
EDIT: While putting the numbers in parenthesis doesn't seem necessary, I'd recommend it anyway to make it clear what is the range and what is the decimal point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With