如何返回数组中最小整数的索引?

时间:2015-12-02 02:31:25

标签: arrays ruby indexing minimum

我正在返回数组中最小整数的索引。我从这个论坛找到了解决方案。这是我做的:

require 'amatch'
include Amatch

ingredients_arr = [
  "All purpose", "Ammoniaco", "Assorted sprinkles", "Baking Powder",
  "Baking soda", "Banana", "Banana flavor", "Bread improver", "Brown Sugar",
  "Buko pandan flavor", "Butter", "Butter flavor", "Butter oil subs",
  "Cake Flour", "Cake emulsi\nfier", "Canyon baking powder", "Cheese",
  "Chiffon oil", "Choco flavor", "Choco spri\nnkles", "Cocoa (imp)",
  "Cocoa (loc)", "Coconut", "Condensada", "Cooking\nOil", "\n    Corn Starch",
  "Dessicated", "Dutch choco fudge premium", "Dutch cocoa premium", "Egg",
  "Evaporad\n    a (B)", "Evaporada (S)", "Evaporadaorated\n(B)", "First Class",
  "Food color", "Glucose", "Go\n    ld coin", "Heart sprinkles", "LPG", "Lard",
  "Linga", "Margarine", "Mocha flavor", "Mongo paste red", "Onion", "Ovalet",
  "Powdered sugar", "Rhum", "Royal", "Salt", "Sibuyas", "Skim milk (h-end)",
  "Skim milk (l-end)", "\n    Star sprinkles", "Strawberry flavor",
  "Styro (l. plan)", "Super syrup", "Taba", "Tartar", "\n    Third Class",
  "Ube Paste", "Ube flavor", "Vanilla", "Vanilla 1G", "Vivid icing",
  "Wash Sugar", "Water", "White Sugar"
]
i, ingredient = 1, "Flour"
ing_array = Array.new
until ingredient == ""
  puts "Enter ingredient #{i}: "
  ingredient = gets.chomp
  ing_array << ingredient
  i += 1
end
ing_array.pop
m = Sellers.new("margarine")
no_words = ing_array.length
ing_index_arr = Array.new
i = 0
while i < no_words
  rating_arr = Array.new
  m = Sellers.new(ing_array[i])
  j = 0
  while j < ingredients_arr.length
    x = m.match(ingredients_arr[j])
    rating_arr << x
    j += 1
  end
  y = rating_arr.each.with_index.find_all{|a, i| a == rating_arr.min }.map{|a, b| b}
  ing_index_arr << y
  i += 1
end
ing_index_arr # => [[0], [67], [4]]

但我需要这样的事情:

[0, 67, 4]

希望有人可以帮助我。

2 个答案:

答案 0 :(得分:1)

如果要折叠子数组,请使用flatten方法。 http://ruby-doc.org/core-2.2.0/Array.html#method-i-flatten

[[0],[67],[4]].flatten == [0,67,4]

答案 1 :(得分:1)

我不确定我是否理解你。 如果你想得到数组中最小整数的索引你可以简单地对它进行排序。

  

阵列= [2,9,90,345]
  
的Array.sort   =&GT; [1,9,90,345]

在这种情况下,最低整数始终为index = 0

当你有数组= [2,3,4]时,它已经是数字:

  

数组[0]的.class
  =&GT; Fixnum对象