Reputation: 15
Let's say that I have a multidimensional array with array's inside of it that each have two numbers. How do I iterate over the entire array and output the lowest number in each array? For example [[4, 6][8, 3]].My attempts at using .min, <=>, and if else statements have not worked.
Upvotes: 0
Views: 629
Reputation: 11188
Just use flatten followed by min like so:
[[4, 6], [8, 3]].flatten.min
=> 3
Upvotes: 1
Reputation: 52346
Should be as simple as:
[[4, 6],[8, 3]].each{|a| puts a.min}
or
[[4, 6],[8, 3]].map{|a| a.min}
... for an array output
Upvotes: 2
Reputation: 1604
Assuming you want to list 'all the mins from the arrays', there are lots of ways, here is a simple one:
array_of_arrays = [[4,6],[8,3]]
lowest_arrays = array_of_arrays.map {|a| a[0] < a[1] ? a[0] : a[1]}
or
lowest_arrays = array_of_arrays.map {|a| a.min}
This outputs [4, 3]
Upvotes: 2