require 'rubygems'

无人久伴 提交于 2019-12-03 11:33:07

问题


I have seen many samples of Ruby code with this line (for example, http://www.sinatrarb.com/). What is purpose of this require?

# require 'rubygems'
require 'sinatra'
get '/hi' do
  "Hello world!"
end

In all cases the code works without this line.


回答1:


It is often superfluous. It will allow you to require specific versions of particular gems though, with the gem command.

https://guides.rubygems.org/patterns/#requiring-rubygems




回答2:


require 'rubygems' will adjust the Ruby loadpath allowing you to successfully require the gems you installed through rubygems, without getting a LoadError: no such file to load -- sinatra.

From the rubygems-1.3.6 documentation:

When RubyGems is required, Kernel#require is replaced with our own which is capable of loading gems on demand.

When you call require 'x', this is what happens:

  • If the file can be loaded from the existing Ruby loadpath, it is.

  • Otherwise, installed gems are searched for a file that matches. If it's found in gem 'y', that gem is activated (added to the loadpath).

The normal require functionality of returning false if that file has already been loaded is preserved.

See the documentation for Kernel#require to understand why this is necessary.




回答3:


As an addition to prior (and correct answers): Ruby 1.9 and newer ship with RubyGems built-in, so there is no real need to require 'rubygems'. Source here



来源:https://stackoverflow.com/questions/2711779/require-rubygems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!