Ruby on Rails Coding Interview Question: Find the Second Largest Number in an Array

Gokul
4 min readMay 28, 2023

Preparing for a Ruby on Rails coding interview may be a stressful commitment. With the correct information and practice, though, you can confidently demonstrate your skills and obtain your desired job. I present a detailed list of frequent Ruby on Rails coding interview questions in this blog article to help you prepare efficiently.

I encourage readers to practice coding challenges, review the Rails documentation, and seek additional resources to enhance their understanding of Ruby on Rails. Armed with this knowledge, you’ll be well-equipped to excel in Ruby on Rails coding interviews and secure your desired position in web development.

Question

Write a Ruby method to find the second-largest number in an array

Solution 1

def second_largest(arr)
arr.max(2).min
end

puts second_largest([5, 8, 2, 9, 1]) #=> 8
  • arr.max(2) is used to find the two largest numbers in the array. It returns an array containing the two maximum values from the original array. In this case, it would return [9, 8].
  • .min is then called on the resulting array from step 1 to find the minimum value, which corresponds to the second largest number. In this case, it would…

--

--

Gokul
Gokul

Responses (1)