[RUBY] Linear search problem for arrays

Introduction

As for programming and algorithms, I'm a beginner and I (probably) solved the problem of linear search, so it's not a big deal (I'm happy), but I wrote an article.

Problems and sources

If there is a matching number in the array, output it with the index number of the array. If not, there is no output.

array = [3, 5, 9 ,12, 15, 21, 26, 34, 42, 51, 55, 56, 62, 65, 74, 123]

def search(a,array)
  count = 0
  array.each_with_index  do |num, i|
    if num == a 
      puts "#{i}It is in the second."
    else
    count = count + 1
    end
  end
  if count == array.length
    puts "That number is not included"
  end
end

search(5,array)

In addition to this, there seems to be a method of returning the process when the condition is true as return instead of describing else and later, and outputting when it is not outside the repeated process. Then you can create a method like an if statement that includes iterative processing.

Finally

It's my first post, so I'm nervous and happy, but I'm sorry to post it.

Recommended Posts

Linear search problem for arrays
Linear search
ruby search problem
Practice of linear search method
[Ruby] Search problem using index method
Search for English words from terminal