There's no simple yes or no answer. You'd need to specify the year and model of both the Ranger and the 4.0L engine you're considering. Even then, it's not just a matter of physical space; you'd also need to consider:
* Engine mounts: The 4.0L engine's mounts will likely not align with the existing 3.0L mounts. Custom fabrication would be required.
* Transmission: The transmission from the 3.0L might not be compatible with the 4.0L.
* Wiring harness and computer: Significant electrical work would be needed to integrate the 4.0L's system.
* Exhaust system: The exhaust system will need modification or replacement.
* Driveshafts: Potential length differences may necessitate changes.
* Cooling system: The 4.0L may require a different radiator or cooling fan setup.
In short, while *physically* fitting might be possible in *some* Ranger years, it's a significant undertaking requiring considerable mechanical expertise and custom fabrication. It's not a straightforward bolt-in swap. You should consult forums dedicated to your specific year Ranger to see if others have attempted this and what challenges they encountered.