Why will my if and els-if statement within my ruby method not work

105 Views Asked by At

I am trying to create a ruby class with a method that takes ages into account. While the if elsif method works for producing 100 fruits for trees over the age of 5 and less than 10. Any tree over the age of 10 and less than 15 should produce 200 but don't?

def grow_fruits
    if @age <= 5
      @fruits = 0
    elsif @age < 10
      @fruits = 100
    elsif @age < 15
      @fruits = 200
    else
      @fruits = 0
    end
  end

I have tired @age <= 10 && @ < 15 but agai no response?

1

There are 1 best solutions below

6
Jad On

Your code appears to work correctly:

# additional set variables before your code
@age=0
@fruits=0

# your code
def grow_fruits
  if @age <= 5
    @fruits = 0
  elsif @age < 10
    @fruits = 100
  elsif @age < 15
    @fruits = 200
  else
    @fruits = 0
  end
end

testing output:

2.7.2 :015 > grow_fruits
 => 0
2.7.2 :016 > @age=10
 => 10
2.7.2 :017 > grow_fruits
 => 200
2.7.2 :018 > @age=14
 => 14
2.7.2 :019 > grow_fruits
 => 200
2.7.2 :020 > @age=9
 => 9
2.7.2 :021 > grow_fruits
 => 100

personally, I hate using instance variables, in a "global variable" way, and would want to pass in the number that was being checked:

def grow_fruits(age=0)
  # remember triple-dots exclude the end value, useful for float comparison
  case age
  when 5...10
    100
  when 10...15
    200
  else
    0
  end
end

testing:

2.7.2 :035 > grow_fruits(0)
 => 0
2.7.2 :036 > grow_fruits(10)
 => 200
2.7.2 :037 > grow_fruits(14)
 => 200
2.7.2 :038 > grow_fruits(9)
 => 100
2.7.2 :039 > grow_fruits(21)
 => 0

if you really wanted to set the instance @fruits variable, you would be better off doing this:

@fruits = grow_fruits(@age)