Eats Indigo Eats Indigo - 5 years ago 279
Ruby Question

How can I avoid error when setting elsif range condition?

def Summer
@summer = true
puts "Your fruit are ripe for the picking."
if @tree_age == 1..5 && @tree_age > 0
@oranges = 5
elsif @tree_age == 6..15
@oranges = 20
else
@oranges = 50
end
end


I'm trying to ensure a tree between a certain age range gives x oranges, however I'm stuck with the following error referring to my elsif statement:

Orange_tree.rb:14: warning: integer literal in conditional range


I have also tried using an if greater than && less than conditional statement, can somebody please explain what this error means, and how to reach my solution.

Answer Source

You should use include? instead of == to determine if the given number is within the range:

def Summer
    @summer = true
    puts "Your fruit are ripe for the picking."
    if (1..5).include?(@tree_age) && @tree_age > 0
        @oranges = 5
    elsif (6..15).include? @tree_age
        @oranges = 20
    else
        @oranges = 50
    end
end

==:

Returns true only if obj is a Range, has equivalent begin and end items (by comparing them with ==), and has the same exclude_end? setting as the range.

Which is obviously not the case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download