Getting an error when installing 'sudo gem install mechanize'

Even I have installed ruby-dev and ruby-make but still giving same error ? how to fix the error ?

sudo gem install mechanize
    Building native extensions.  This could take a while...
    ERROR:  Error installing mechanize:
        ERROR: Failed to build gem native extension.

        current directory: /var/lib/gems/2.4.0/gems/unf_ext-
    /usr/bin/ruby2.4 -r ./siteconf20180417-8728-15wdd1s.rb extconf.rb
    mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

    extconf failed, exit code 1

    Gem files will remain installed in /var/lib/gems/2.4.0/gems/unf_ext- for inspection.
    Results logged to /var/lib/gems/2.4.0/extensions/x86_64-linux/2.4.0/unf_ext-

1 answer

  • answered 2018-04-17 04:21 anothermh

    You don't have the source code for Ruby so when it attempts to compile the gem it fails. It's looking for /usr/lib/ruby/include/ruby.h but that file isn't present on your system.

    Generally, it's not a good idea to use the system version of Ruby. (for this reason, and others) You should use a Ruby manager to install Ruby into your user profile, as this will make compiling gems a lot easier.

    For example, you can use RVM to install Ruby:

    \curl -sSL | bash -s stable

    This will install the latest version of rvm, which you can then use to install Ruby 2.4:

    rvm install 2.4

    You can install nearly any version of Ruby by specifying its version, for example Ruby 2.5:

    rvm install 2.5

    Afterwards, running ruby will automatically run the version installed by RVM. And since it's installed in your profile, you don't need to use sudo for any operations. (and you should never use sudo when using rvm or Rubies installed by rvm)

    In your case, you would then be able to run gem install mechanize successfully because it would be using the Ruby installation in your home directory that includes a copy of the source code and header files.

    If for some reason you can't use RVM or don't want to use RVM, then you need to have the Ruby header files installed. The way to install these headers varies by operating system so there's no one answer I can give you. If your OS is a Debian-based version of Linux, for example, you can install the headers with:

    sudo apt-get install ruby2.4-dev

    More information is available in another answer on stackoverflow.