lundi 5 février 2018

If statement in ruby seems to give only the else result

As said in the title, whatever result I set as input, it always gives the else's result which means F. I've spent some time searching why, but I can't figure it out. I'm used to Java as a language and I'm just starting ruby, so I'm trying to code accordingly to what I know in Java and maybe this might be the mistake.

class Test
  @g1
  @g2
  @g3
  @avg
  @grade
  def initialize(g, gg, ggg)
    @g1 = g
    @g2 = gg
    @g3 = ggg
  end

  def setAVG
    @avg = (@g1.to_f + @g2.to_f + @g3.to_f)/3.0
  end

  def getScore
    if @avg.to_f >= 90 and @avg.to_f <= 100
      @grade = 'A'
    elsif @avg.to_f >= 80 and @avg.to_f <= 89
        @grade = 'B'
    elsif @avg.to_f >= 70 and @avg.to_f <= 79
      @grade = 'C'
    elsif @avg.to_f >= 60 and @avg.to_f <= 69
      @grade = 'D'
    else
      @grade = 'F'
    end

    @grade

  end

end

puts 'Enter g1'
gr1 = gets()

puts 'Enter g2'
gr2 = gets()

puts 'Enter g3'
gr3 = gets()

gradesArr = [gr1, gr2, gr3]

for g in 0..gradesArr.length
  if gradesArr[g].to_f <0 or gradesArr[g].to_f > 100
    puts "Reset program with correction at the #{g+1} grade"
    abort
  end
end

grObj = Test.new(gr1,gr2,gr3);

puts "YOUR GRADE IS:  #{grObj.getScore}     #{grObj.setAVG}"

Also feel free to tell me if these are the ruby standards, for example, I know that in java you generally type return for a get method, but in ruby, you just write the variable.

Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire