Personally I do not recommend you to perform the installation using
sudo gem install rails
Since this will install a specific version of rails on your system and make it available, the future problem could be having to open an application in a different version of rails or even some gems, so it is recommended to use version handlers as rvm or rbenv
The reason for the error message is that ruby does not find some necessary libraries as prerequisites for rails, this is because ruby is a language that for performance reasons prefers to interact directly with the native libraries of the operating system.
You could solve it with:
sudo apt-get install libxml2-dev zlib1g-dev
If you are going to use a version manager as recommended, be sure to execute this command first so you do not have to install it later in the context of the version manager.