Ruby

Day 19 of 30 - Ruby Coding Challenge - Finding the Missing Number - Ruby Way

Day 19 of 30 - Ruby Coding Challenge - Finding the Missing Number - Ruby Way

Hey friends!

This is the blog post version of the Youtube video from the 30 Ruby Coding Challenges in 30 Days series

Today we want to solve the previous puzzle using a more Ruby/Decent way to solve problems. Let’s get into it!

Previous Algorithm Version

The previous algorithm version looks like this:

def find_missing_num(array)
  (1..10).each do |item|
    found = false
    array.each do |number|
      if item == number
        found = true
        break
      end      
    end
    if found = false
      return item
    end
  end
end

array = [1, 2, 3, 4, 6, 7, 8, 9, 10]
find_missing_num(array)

New Algorithm Version

It’s time to avoid manipulating the array manually. We can easily do that by using the method include?() on the array

arr.include?(number)

The simple and complete code could be:

def missing_num(arr)
  (1..10).each do |num|
    return num unless arr.include?(num)
  end
end

array = [1, 2, 3, 4, 5, 7, 8, 9, 10]
missing_num(array)

Pretty simple, isn’t it? 😎

Do you have a better/different way to solve this? Drop your comment on the Youtube video and bring more ideas to the community 😄

See you in the next coding challenge :)

Don’t forget to come by and say hi Alex

Courses Twitter Youtube Instagram Linkedin GitHub

Join My Newsletter

You’ll receive coding courses, tutorials and personal posts! I’ll be happy to send them to you, weekly :)