Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple conditions in one if-statement in Ruby Language

I write something like this in 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 and b both are unique arrays.

Is there any way to check all if and elsif's in the same condition?

Only one condition for a[0], a[1], a[2] and a[3]?

like image 466
elixir Avatar asked Dec 04 '22 17:12

elixir


1 Answers

Array#index might help in cases like these (assuming the size of a and b is the same):

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

In cases in which the array a might be empty, you will need an additional condition to avoid an error:

index = a.index(a.max)
brand = b[index] if index
like image 93
spickermann Avatar answered Jan 10 '23 20:01

spickermann