Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range with decimal place

Tags:

arrays

ruby

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

like image 966
Stacker-flow Avatar asked Mar 22 '23 18:03

Stacker-flow


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 @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 }
like image 147
Arup Rakshit Avatar answered Apr 03 '23 19:04

Arup Rakshit


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.

like image 22
Linuxios Avatar answered Apr 03 '23 21:04

Linuxios