【发布时间】:2018-12-29 18:56:46
【问题描述】:
这是我的任务:
输入:来自键盘的数字列表
输出:列表中第二小的数字,以及它在列表中的位置,其中 1 是第一个数字的位置。
到目前为止,这是我的代码:
values = []
print "Enter a number: "
a = gets.chomp.to_i
values.push(a)
print "Enter another number: "
b = gets.chomp.to_i
values.push(b)
print "Enter another number: "
c = gets.chomp.to_i
values.push(c)
print "Enter a final number: "
d = gets.chomp.to_i
values.push(d)
new_values = values.sort
second_smallest = new_values[1]
puts "Second smallest number: #{second_smallest}"
if values.include? second_smallest
print "found matching element"
end
我能够从排序后的副本中获取第二小的元素,然后在原始数组中检查该元素。如何获取原始数组中匹配元素的索引并将其打印给用户?
对不起,如果它很简单,我是 ruby 的新手
【问题讨论】:
-
获取数组中某个值的索引并不难。数组有一个index 方法。
标签: arrays ruby indexing matching