How can I return the index of the minimum integer in an array?

I'm returning the index of the smallest integer in an array. I found a solution from this forum. Here is what I did:

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]]

but I need something like this:

[0, 67, 4]

Hope someone can help me.

Answers


If you want to collapse your sub-arrays, use the flatten method. http://ruby-doc.org/core-2.2.0/Array.html#method-i-flatten

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

I'm not sure if I understood You correctly. If you want to get index of the smalleest integer in the array You can simply sort it.

array=[2,9,90,345] array.sort => [2, 9, 90, 345]

In this case the lowest integer would have always an index=0

When you have array=[2,3,4] it is already numeric:

array[0].class => Fixnum


Need Your Help

NullReferenceException: Object reference not set to an instance of an object. in a foreach loop

c# .net html asp.net-mvc

I'm having trouble with the instance of my object it gave me an error in which i don't understand

Trigger a click when handling a focus event (jQuery)

javascript jquery events javascript-events

I'm trying to determine why something like this doesn't work: