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两者都是唯一的数组。
有什么方法可以检查所有if和elsif的情况相同吗?
只有一个条件a[0], a[1],a[2]和a[3]?
阵列#指数可能有助于在这样的情况下(假设的大小a和b是一样的):
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)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |