Utilisation de plusieurs conditions dans une instruction if en Ruby Language

Nov 24 2020

J'écris quelque chose comme ça en 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

aet les bdeux sont des tableaux uniques.

Existe-t-il un moyen de vérifier tous les ifet elsifest dans le même état?

Une seule condition a[0], a[1], a[2]et a[3]?

Réponses

6 spickermann Nov 24 2020 at 17:03

L'index Array # peut aider dans des cas comme ceux-ci (en supposant que la taille de aet best la même):

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

Dans les cas où le tableau apourrait être vide, vous aurez besoin d'une condition supplémentaire pour éviter une erreur:

index = a.index(a.max)
brand = b[index] if index
4 CarySwoveland Nov 24 2020 at 17:33

Deux autres façons:

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

ou

b[a.each_with_index.max_by(&:first).last]
  #=> 5
4 Stefan Nov 24 2020 at 17:55

En supposant aet bavoir la même taille, par exemple

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

vous pouvez combiner zipet 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

ou max_byet with_index:

b.max_by.with_index { |_, i| a[i] }
#=> :c
2 TimurShtatland Nov 24 2020 at 17:30

Si votre tableau a plusieurs maxima, vous voudrez peut-être obtenir les indices du tableau qui correspondent à tous les 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]