繁体   English   中英

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

[英]Using multiple conditions in one if-statement in Ruby Language

我在 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

ab都是唯一的数组。

有没有办法检查所有ifelsif的条件相同?

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

Array#index在这些情况下可能会有所帮助(假设ab的大小相同):

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

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

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

还有两种方式:

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

假设ab具有相同的大小,例如

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

你可以结合zipmax

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_bywith_index

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

如果您的数组有多个最大值,您可能想要获取对应于所有最大值的数组索引:

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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