I am reviewing the drill to strengthen my logical thinking. As a beginner, I would appreciate it if you could let me know if you have any questions. This time is my failure story.
From the following array, create a search method using each_with_index that searches for a number and returns the result of what number it is included in.
ruby.rb
input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
ruby.rb
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(11, input)
#result
That number is not included
ruby.rb
def search(target_num, input)
input.each_with_index do |num, index|
if num == target_num
puts "#{num}Is#{index + 1}It is in the second."
else
puts "#{num}Is not included."
end
end
end
input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
search(12, input)
#result
3 is not included.
5 is not included.
9 is not included.
12 is in fourth place.
15 is not included.
21 is not included.
29 is not included.
35 is not included.
42 is not included.
51 is not included.
62 is not included.
78 is not included.
81 is not included.
87 is not included.
92 is not included.
93 is not included.
The processing result has been output for all the elements of the input array passed as an argument. Furthermore, since else is used for conditional branching, if they do not match, even if they exist in the array, they will be displayed as "not included".
Therefore, the following two points are required. ① Eliminate else ② Stop with return
(1) Since each_with_index is an iterative process, it will check each value in the input array. Therefore, if else is placed, each result will also be displayed, so only if.
ruby.rb
input.each_with_index do |num, index|
if num == target_num
puts "#{index + 1}Is in the second"
end
end
And when all the values in each_with_index's array have been checked, As a result, I want you to return "not included", so put puts outside the conditional branch + iterative processing.
ruby.rb
def search(target_num, input)
input.each_with_index do |num, index|
if num == target_num
puts "#{index + 1}Is in the second"
end
end
puts "That number is not included"
end
(2) Even if the existence of the desired numerical value can be confirmed, "the number is not included" will be displayed if it is left as it is. It looks like the following.
ruby.rb
def search(target_num, input)
input.each_with_index do |num, index|
if num == target_num
puts "#{index + 1}Is in the second"
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)
#result
4th
That number is not included
If you can confirm the existence of the value, you want to end the method at that point, so put a return after displaying "It is in the ◯ th".