2012-03-09 130 views
1

我可以使用红宝石安装json库。如果它是相关的,我使用的是最新的OS X.如何在OS X上安装宝石后使用红宝石

usr$ sudo gem install json 
Password: 
Building native extensions. This could take a while... 
Successfully installed json-1.6.5 
1 gem installed 
Installing ri documentation for json-1.6.5... 
Installing RDoc documentation for json-1.6.5... 

但是,试图require 'json'这是行不通的。我究竟做错了什么?

touakas-MacBook-Pro:tmp jacob$ ruby x.rb 
x.rb:3:in `require': no such file to load -- json (LoadError) 
    from x.rb:2 

的x.rb如下:

#!/usr/bin/env ruby 
require 'json' 

x = { "a"=>"b" } 
print x.to_json 
+0

你能不能给这个一杆:'红宝石-rubygems x.rb' – Candide 2012-03-09 10:16:00

+0

JSON是红宝石1.9.x的STD-lib的HTTP的一部分:// WWW。 ruby-doc.org/stdlib-1.9.3/libdoc/json/rdoc/JSON/Ext/Generator/GeneratorMethods/Hash.html – 2012-03-09 10:40:02

回答

5

您需要先加载的RubyGems:

require 'rubygems' 
require 'json' 

编辑:

根据下面的评论,你最好使用ruby -rubygems x.rb而不是require rubygems directl y(假设你正在为resue编写一个模块)。

感谢: @injekt和@Ingenu

+0

Whoot!谢谢!! – Jacob 2012-03-09 11:54:07

+0

请避免使用'require'rubygems''并且像@Ingenu在他们的评论中所说:'ruby -rubygems x.rb' - 请参阅http://www.rubyinside.com/why-using-require-rubygems-is -wrong-1478.html了解更多信息 – 2012-03-09 12:06:29