BerryGJS
BerryGJS

Reputation: 119

Match/compare a value with members of an array

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

Answers (4)

Stefan
Stefan

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

hirolau
hirolau

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

sawa
sawa

Reputation: 168131

[0..25, 26..50, 51..75, 76..100].find{|r| r.include?(28)} # => 26..50

Upvotes: 5

rhenvar
rhenvar

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

Related Questions