简体   繁体   中英

Using multiple conditions in one if-statement in Ruby Language

I write something like this in Ruby:

if a.max == a[0] 
  brand = b[0]
elsif a.max == a[1]
  brand = b[1]
elsif a.max == a[2]
  brand = b[2]
elsif a.max == a[3]
  brand = b[3]
end

a and b both are unique arrays.

Is there any way to check all if and elsif 's in the same condition?

Only one condition for a[0] , a[1] , a[2] and a[3] ?

Array#index might help in cases like these (assuming the size of a and b is the same):

brand = b[a.index(a.max)]

In cases in which the array a might be empty, you will need an additional condition to avoid an error:

index = a.index(a.max)
brand = b[index] if index

Two more ways:

a = [3, 1, 6, 4]
b = [2, 8, 5, 7]
b[a.each_index.max_by { |i| a[i] }]
  #=> 5

or

b[a.each_with_index.max_by(&:first).last]
  #=> 5

Assuming a and b have the same size, eg

a = [2, 5, 8, 1]
b = [:a, :b, :c, :d]

you could combine zip and max :

a.zip(b).max.last  # or more explicit: a.zip(b).max_by(&:first).last
#=> :c             # or reversed:      b.zip(a).max_by(&:last).first

or max_by and with_index :

b.max_by.with_index { |_, i| a[i] }
#=> :c

If your array has multiple maxima, you may want to get the indices of the array that correspond to all the maxima:

a = [10, 12, 12]
b = [:a, :b, :c]

# Compute and store the maximum once, to avoid re-computing it in the
# loops below:
a_max = a.max

idxs = a.each_with_index.select{ |el, idx| el == a_max }.map{ |el, idx| idx }
# or:
idxs = a.each_with_index.map{ |el, idx| idx if el == a_max }.compact

puts "#{idxs}"
# [1, 2]

puts "#{idxs.map{ |idx| b[idx] }}"
# [:b, :c]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM