另一个解决边缘情况的解决方案......
@size_hash = {
'Large' => 70..139,
'Medium' => 15..69,
'Small' => 1..14,
}
some_value = @size_hash["Small"]
@min = some_value.first
@max = some_value.last
@size_hash.each_pair do |k, v|
@min = [@min, v.first].min
@max = [@max, v.last].max
end
puts "size_hash goes from #{@min} to #{@max}"
# Given a number, return the name of the range which it belongs to.
def whichSize(p_number)
@size_hash.each_pair do |k, v|
return k if v.include?(p_number)
end
return "below minimum" if p_number < @min
"above maximum" if p_number > @max
end
# test
[-10, 0, 1, 10, 14, 15, 20, 69, 70, 80, 139, 140, 1000].each do |e|
puts "size of #{sprintf("%4s", e)} is #{whichSize(e)}"
end
$ ruby -w t.rb
size_hash goes from 1 to 139
size of -10 is below minimum
size of 0 is below minimum
size of 1 is Small
size of 10 is Small
size of 14 is Small
size of 15 is Medium
size of 20 is Medium
size of 69 is Medium
size of 70 is Large
size of 80 is Large
size of 139 is Large
size of 140 is above maximum
size of 1000 is above maximum