在 Ruby 语言中的一个 if 语句中使用多个条件

eli*_*xir 4 ruby arrays loops if-statement max

我在 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
Run Code Online (Sandbox Code Playgroud)

a并且b两者都是唯一的数组。

有什么方法可以检查所有ifelsif的情况相同吗?

只有一个条件a[0], a[1],a[2]a[3]?

spi*_*ann 6

阵列#指数可能有助于在这样的情况下(假设的大小ab是一样的):

brand = b[a.index(a.max)]
Run Code Online (Sandbox Code Playgroud)

在数组a可能为空的情况下,您将需要一个额外的条件来避免错误:

index = a.index(a.max)
brand = b[index] if index
Run Code Online (Sandbox Code Playgroud)