In the array,
input = [1, 3, 5, 6, 10, 14, 17, 21, 27, 33, 39, 41, 48]
Is included. You can use the serch method to return the result of what number the value is included in. Example)
search(17, input)
#Result of processing
#=>6th
search(1, input)
#Result of processing
#=>That number is not included
The usage example looks like this.
I would like to create this search method using the each_with_index method. The each_with_index method is a method built into Ruby as standard, and it can indicate the number of processing of the element at the same time as repeating the element. reference: Ruby 3.0.0 Reference Manual, each_with_index
Example)
fruits = ["Strawberry","Mandarin orange"."Grape"]
fruits.each_with_index do |item, i|
puts "#{i}The second fruit is#{item}is."
end
#Output result
#The 0th fruit is melon.
#The first fruit is banana.
#The second fruit is apple.
You can use it like this.
Well then, I would like to get into the main subject. First, I would like to think about how to call the search method. Let's define an array and set some number as an actual argument when calling it. This time I would like to set a value of 17.
def search(target_num, input)
end
input = [1, 3, 5, 6, 10, 14, 17, 21, 27, 33, 39, 41, 48]
search(17, input)
In the search method called by search (17, input), the value set by the actual argument is received by the formal argument (target_num, input). This time target_num receives 17 and input receives input (the contents are assigned an array).
Next, I would like to consider the processing inside the search method. Use the each_with_index method to retrieve the contents of the array one by one and get the subscripts assigned to each element at the same time.
def search(target_num, input)
input.each_with_index do|num, index|
end
end
Finally, we will use conditional bifurcation processing to describe the values in the array and the processing when they are not. When combined, the description is as follows.
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 = [1, 3, 5, 6, 10, 14, 17, 21, 27, 33, 39, 41, 48]
search(17, input)
When num and target_num are equal, puts "# {index + 1} is at the th" is output. The reason for index +1 is that the program counts from 0.
Since humans basically count from 1, index +1 is used to fill in the error in counting programs.
Recommended Posts