Home > katas > Find the smallest integer in the array (8kyu) [Ruby]

Find the smallest integer in the array (8kyu) [Ruby]


Chek kata on Codewars

Description:

Given an array of integers your solution should find the smallest integer.

For example:

Given [34, 15, 88, 2] your solution will return 2
Given [34, -345, -1, 100] your solution will return -345
You can assume, for the purpose of this kata, that the supplied array will not be empty.

Solution 1

Let's start with loop solutions.

def find_smallest_int(arr)
  smallest = arr[0]

  arr.each do |num|
    if num < smallest
        smallest = num
    end
  end

  smallest
end

Solution 2

Let's solve it with min.

def find_smallest_int(arr)
  arr.min
end

Solution 3

Let's solve it with sort().

def find_smallest_int(arr)
  arr.sort()[0]
end

Solution 4

Let's solve it with reduce().

def find_smallest_int(arr)
    arr.reduce() { |acc, cur| acc < cur ? acc : cur}
end
© 2021, Andrew Losseff