coding for food

[Ruby] EXERCISES _ First In Array

silveryen 2022. 7. 28. 11:00

exercise

def first_in_array(arr, el1, el2)

end

puts first_in_array(["a", "b", "c", "d"], "d", "b"); # => "b"
puts first_in_array(["cat", "bird" ,"dog", "mouse" ], "dog", "mouse"); # => "dog"

 

my code

def first_in_array(arr, el1, el2)
  
  arr.each do |char|
  
    if (char == el1) || (char == el2)
    return char
    end
  
  end
  

end

puts first_in_array(["a", "b", "c", "d"], "d", "b"); # => "b"
puts first_in_array(["cat", "bird" ,"dog", "mouse" ], "dog", "mouse"); # => "dog"

solution

def first_in_array(arr, el1, el2)
  if arr.index(el1) < arr.index(el2)
    return el1
  else
    return el2
  end
end

puts first_in_array(["a", "b", "c", "d"], "d", "b"); # => "b"
puts first_in_array(["cat", "bird" ,"dog", "mouse" ], "dog", "mouse"); # => "dog"