I will write it for output. `Use Ruby 2.6.5 installed on macOS Catalina 10.15.6. ``
You want to create a method using ** search ** and ** each_with_index ** that looks for a number and returns the result of what number it is included in.
input = [3, 5, 9 ,12, 15, 21, 29, 35, 42, 51, 62, 78, 81, 87, 92, 93]
search(12, input)
=>4th
search(7, input)
=>That number is not included
** each_with_index ** is one of the standard methods built into Ruby. At the same time as iterating the element, you can also show what number the element was processed.
#each_with_How to use index
Array name.each_with_index do |item, i|
end
** More detailed examples of using each_with_index **
cigarettes = ["MEVIUS", "highlight", "LuckyStrike"]
cigarettes.each_with_index do |item, i|
puts "#{i}The second cigarette is#{item}is."
end
If you execute this ↑, you will get the following output result.
The 0th cigarette is MEVIUS.
The first cigarette is highlight.
The second cigarette is Lucky Strike.
array.rb
def search(tage_i, input)
input.each_with_index do |i, index|
if i == tage_i
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
By the way, let's output the numbers that apply ...
array.rb
def search(tage_i, input)
input.each_with_index do |i, index|
if i == tage_i
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)
search(29, input) #Addition of numbers that meet the conditions of "~ th!"
Can you think slowly and carefully ...? I can't deny that I can only understand the surface, so I'll take a note. I think I will update it again.
Recommended Posts