Ruby 언어에서 하나의 if 문에 여러 조건 사용

Nov 24 2020

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그리고 b모두 독특한 배열입니다.

ifelsif의 모두 동일한 상태 인지 확인할 수있는 방법이 있습니까?

하나의 조건 a[0], a[1], a[2]a[3]?

답변

6 spickermann Nov 24 2020 at 17:03

Array # index 는 다음과 같은 경우에 도움이 될 수 있습니다 ( a과 크기가 같다고 가정 b).

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

배열 a이 비어있을 수있는 경우 오류를 방지하기위한 추가 조건이 필요합니다.

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

두 가지 방법이 더 있습니다.

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

또는

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

예를 들어 같은 크기 라고 가정 a하고b

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

당신은 결합 수 zip와 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

또는 max_by및 with_index:

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

배열에 다중 최댓값이있는 경우 모든 최댓값에 해당하는 배열의 인덱스를 가져올 수 있습니다.

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]