As the title says. Let's write the code using the each_with_index method.
A method that can indicate the number of processing of an element at the same time as iterating the element. You can use each method if it is an iterative process of elements, The feature of each_with_index method is that it can also display what number was processed. Write as follows.
Array name.each_with_index do |item, i|
#processing
end
fruits = ["Mandarin orange", "pineapple", "Apple"]
fruits.each_with_index do |fruit, i|
puts "#{i}The second fruit is#{fruit}is."
end
The output result is as follows.
The 0th fruit is mandarin orange.
The first fruit is pineapple.
The second fruit is an apple.
A method that searches if an array contains a certain value and outputs the result Let's write it using each_with_index method. ~~ You can use binary search without using the each_with_index method ~~
The array is
input = [3, 6, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
Suppose you want to assign the value you want to search to the variable target_num
.
Make sure you get the following search results.
#When the value you want to search for is in the array. For example, if the value you want to search for is 12.
Fourth from the left
#When the value you want to search is not in the array
That number is not included
def search(target_num, input)
input.each_with_index do |num, index|
if num == target_num
puts "From the left#{index + 1}Is in the second"
return
end
end
puts "That number is not included"
end
input = [3, 6, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
target_num = gets.to_i
search(target_num, input)
This time, the method that performs the search process is defined as the search method.
In the search method, use each_with_index method
The values stored in the array ʻinput are fetched one by one as
num and numbered in the order they are fetched. That number goes into ʻindex
.
Compare if num
and target_num
(which contains the value you want to search for) are the same.
If they are the same, we want to output the number of the value counting from the left of the array.
puts" # {index + 1} th from the left "
.
And since the search results are already available and no further searches are needed, end with return
.
If all the values stored in the array are not the same as the one you want to find
Let's say puts" that number is not included "
.
that's all. It's a little off the subject, but it's quite difficult to write the commentary. Thank you for reading to the end.
Recommended Posts