Combination of search and each_with_index

The formula that appeared in today's drill.

def search(target_num, input)

  input.each_with_index do |num, index|
    if num == target_num
      puts "#{index + 1}Is in the second"
      return
    end
  end
  puts "That number is not included"
end

input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
search(12, input)

Now you can output "4th".

On the other hand

def search(target_num, input)

  input.each_with_index do |num, index|
    if num == target_num
      puts "#{index + 1}Is in the second"
      return
    else
      puts "That number is not included"
      next
    end
  end
end

input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]

This is using next, The processing in the if statement continues until the fourth 12 appears.

The result is the same without next, Around this time, I thought it would be better to have next in terms of readability.

There was a lot of discussion about this description until before noon. It may be said that it is one of the attractions of programming.

Recommended Posts

Combination of search and each_with_index
[Rails] Differences and usage of each_with_index and each.with_index
Think about the combination of Servlet and Ajax
[Ruby] A program that uses search and each_with_index
[Ruby] A program / concept that combines each_with_index and search
behavior of didSet and willSet
Overview of Docker and containers
Setup of JMeter and jEnv
Background and mechanism of Fabric-loader
Summary of FileInputStream and BufferedInputStream
Implementation of multiple word search, multiple model search, and multiple tag search (acts-as-taggable-on) of ransack
Implementation of sequential search function
Practice of binary search method
[Rails 6] Implementation of search function
Judgment of JSONArray and JSONObject
Operator of remainder and exponentiation (exponentiation)
Advantages and disadvantages of Java
Practice of linear search method
Install Ruby 3.0.0 Preview 1 with a combination of Homebrew and rbenv
Basics of conditional branching and return
Enumeration of combination patterns using List
About fastqc of Biocontainers and Java
Proper use of redirect_to and render
Understand the difference between each_with_index and each.with_index
This and that of the JDK
[Swift] Advantages and disadvantages of Storyboard
Proper use of Mockito and PowerMock
[Java] Judgment of identity and equivalence
About removeAll and retainAll of ArrayList
This and that of Core Graphics
Default implementation of Object.equals () and Object.hashCode ()
Application of downcase and slice methods
This and that of exclusive control
Try writing "Hello, World" with a combination of various languages and libraries