Parameter function with 2 possible types

Hi guys, I am coming to you because for my project, I need a function that can take as parameter a var, that can be a string OR an array of string.

But when I run this function, the compiler complain that the each method don’t exist for a string.
How can I do this ?

My example:

def testy(var : String | Array(String))
  if typeof(var) == String
    puts var
  else
    var.each do |entry|
      puts entry
    end
  end
end

testy("5")

You need to use .is_a? to check the type of a variable:

def testy(var : String | Array(String))
  if var.is_a?(String)
    puts var
  else
    var.each do |entry|
      puts entry
    end
  end
end

testy("5")
1 Like

I’d maybe consider using separate overloads:

def testy(var : String)
  puts var
end

def testy(var : Array(String))
  var.each do |entry|
    puts entry
  end
end

Be a bit cleaner without the conditional logic

4 Likes