TL;DR
No, you can't rely on "the closest version." That may or may not work in a given case, but is unlikely to work at all with severely outdated applications like yours.
You Can't Rely on Newer Versions to Avoid Breaking Changes
Ruby 2.2.1 is past end-of-life. So is Rails 4.0.10.
While Ruby itself more or less follows semantic versioning, Rails follows a modified version where even minor versions can contain breaking changes. Other gems your Rails application relies on may or may not follow semantic versioning at all. So, you can't rely on minor and patch versions to always be backwards-compatible, especially when you're relying on third-party gems in large frameworks like Rails does.
You may also not be able to rely on native extensions to be built the same under different Ruby versions, with different compilers or dynamic library versions, or on different CPU architectures or versions of an OS. At a bare minimum, you need to use the same Ruby and the same Gemfile.lock or you're just asking for trouble.
Other Options
A Ruby version manager like RVM (which contains its own Ruby installer), or rbenv and chruby (both of which require a separate installer for building Ruby versions) will allow you to build and install multiple Rubies, including some older versions, although support for really old versions can sometimes be hit-or-miss.
Since both Ruby 2.2.1 and Rails 4.0.10 are past end-of-life, you may run into problems compiling them or finding outdated dependencies. If that happens, you can try using an official (but unsupported) Docker container for Ruby 2.2.1 with your current Gemfile.lock. If that fails, you may have to use a VM or Docker container with an older version of your OS to properly build your particular Ruby and the Rails application if either has outdated system dependencies.