Ruby: Use .each on anything

While parsing several variables that could be strings or arrays of strings, I found myself doing too much type checking and my code was getting ugly. I wished there was a way to execute each on types that weren’t containers. For instance:

#define variables
$some_path = "/path1"
$some_path2 = ["/path2", "/path3"]
 
# ... some time later ...
$some_path.each {|path| puts path}
$some_path2.each {|path| puts path}

That should produce:

/path1
/path2
/path3

Turns out, this is easy to do. Simply add the each method to the Object class:

class Object
  def each(ary)
    yield self
    return ary
  end
end

I’m not concerned with the index, so this works just fine for my needs