Decimal point range

How to check range with decimal point in ruby?

I want to filter the results in an array between 9.74 - 9.78 in ruby

if (9.74...9.78) == amounts
count += 1
end

It doesn't seem to work

+4
source share
2 answers

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 suggested by @m_x

# 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 }
+6
source

Just put the numbers in parentheses and ===:

if ((9.74)...(9.78)) === amounts
  count += 1
end

EDIT: If putting numbers in parentheses is not necessary, I would recommend it in any case, so that it makes it clear what a range is and what a decimal point is.

+2
source

All Articles