Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum and minimum value in an Array

Tags:

arrays

ruby

I wrote a Ruby code to get max and min values from an array. The code prints the max value (8) correct but it's not printing the minimum value (2). Please let me know what went wrong in my code.

class MaxMinArray
  def MaxMinMethod()
    array = [4,2,8,3,5]
    maxNo = array[0]
    minNo = array[0]
    arrayLength = array.length
    for i in 1..arrayLength
      if array[i].to_i > maxNo
        maxNo = array[i]
      end
      if array[i].to_i < minNo
        minNo = array[i]
      end
    end
    puts "Maximum no. in the given array: " + maxNo.to_s
    puts "Minimum no. in the given array: " + minNo.to_s
  end
end

MaxiMinArrayObj = MaxMinArray.new
MaxiMinArrayObj.MaxMinMethod()
like image 354
ChnMys Avatar asked Nov 30 '22 01:11

ChnMys


1 Answers

It is the combination of two things.

  • First, you iterated over for i in 1..arrayLength, which iterates past the last element in array. After the last element, array[i] is nil.
  • Second, you have the condition if array[i].to_i < minNo, which can be satisfied even if array[i] is not a number.

Because of that, the nil returned by array[i] after the last element satisfies the condition due to nil.to_i being 0, and that nil is assigned to minNo.

like image 168
sawa Avatar answered Dec 19 '22 13:12

sawa