Reputation: 119
I have an array containing four ranges:
[0..25, 26..50, 51..75, 76..100]
How can I match/compare an integer with this array? For example:
28 # => 26..50
89 # => 76..100
What is the best way to do this?
Upvotes: 1
Views: 86
Reputation: 114188
Regarding your comment:
I matched the number with a hash [:range => :score]. So, I have 4 ranges, scoring "bad" "so so" "ok" and "super". If my variable fits a range, it returns the score
You can use a case
statement:
def score(number)
case number
when 0..25 then :bad
when 26..50 then :so_so
when 51..75 then :ok
when 76..100 then :super
end
end
score(28) #=> :so_so
score(89) #=> :super
Upvotes: 1
Reputation: 13911
Or if you just need to know if it matches any range:
p [0..25, 26..50, 51..75, 76..100].any?{|range| range.cover?(my_int) } #=> true
Note that cover?
is faster than include?
, and is safe to use when working with integers.
Upvotes: 0
Reputation: 168131
[0..25, 26..50, 51..75, 76..100].find{|r| r.include?(28)} # => 26..50
Upvotes: 5
Reputation: 98
As @WandMaker said, there are range methods that can help you here
http://ruby-doc.org/core-2.2.0/Range.html#method-i-cover-3F
If I understand your question correctly, you want to check if an int is contained within your ranges?
my_array.each do |range|
if range.cover?(my_integer)
return true
end
end
return false
Upvotes: 1