Stacker-flow
Stacker-flow

Reputation: 1309

Range with decimal place

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

Upvotes: 4

Views: 1578

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

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 }

Upvotes: 5

Linuxios
Linuxios

Reputation: 35803

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.

Upvotes: 2

Related Questions