红宝石在irb会话中需要任意红宝石宝石

时间:2014-10-25 20:03:50

标签: ruby

我一直在玩Rails一段时间。但现在我正在尝试建造一颗红宝石。我正在使用rubymine为你建立一个宝石模板。就我而言,它看起来像这样:

$ ls
bin                 Gemfile       lib          Rakefile   test
binarytree.gemspec  Gemfile.lock  LICENSE.txt  README.md
merlino@johnmerlino:~/Documents/github/binarytree$ 

在lib目录中,我有一个名为binarytree.rb的文件,其中包含以下内容:

require "binarytree/version"

module Binarytree

  class BinaryNode

    attr_accessor :value, :left, :right

    def initialize(value=nil)
      @value = value
      @left = nil
      @right = nil
    end

    def add(value)
      if value <= @value
        if @left
          @left.add value
        else
          @left = BinaryNode.new value
        end
      else
        if @right
          @right.add value
        else
          @right = BinaryNode.new value
        end
      end
    end
  end

  class BinaryTree

    attr_accessor :root

    def initialize
      @root = nil
    end

    def add(value)
      if !@root
        @root = BinaryNode.new value
      else
        @root.add value
      end
    end

    def contains(value)
      node = @root
      while node
        if value == node.value
          return true
        elsif value < node.value
          node = node.left
        else
          node = node.right
        end
      end
      false
    end
  end
end

我想要做的是运行irb(交互式ruby shell)会话,然后能够要求'binarytree'并将此代码放在irb的范围内,所以我可以开始玩它,例如BinaryTree.new。

现在我不知道如何在irb中要求这个:

  

要求'binarytree'   LoadError:无法加载此类文件 - binarytree       来自/home/merlino/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in require' from /home/merlino/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in require'       来自(irb):1       来自/home/merlino/.rvm/rubies/ruby-2.0.0-p0/bin/irb:13:in`'

我在Ubuntu上,我正在使用rvm来管理宝石。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您有两种选择:

  1. 进入宝石目录并运行require './lib/binarytree.rb'
  2. 在宝石目录中运行rake install - 这将构建并将此宝石安装到系统宝石中。

答案 1 :(得分:0)

我按照以下方式工作:

1)您首先需要编辑gemspec:

binarytree.gemspec

并编辑说明和摘要行:

  spec.description   = "binary tree"
  spec.summary       = "binary tree summary"

否则您将收到以下错误:

 gem build doctor_toons.gemspec
ERROR:  While executing gem ... (Gem::InvalidSpecificationException)
    "FIXME" or "TODO" is not a description

2)然后运行gemspec:

gem build binarytree.gemspec

这应输出如下内容:

二叉树-0.0.1.gem

3)现在,如果您使用的是rvm,请确保使用所需的版本,然后运行以下命令:

gem install ./binarytree-0.0.1.gem 

输出应该如下所示:

Successfully installed binarytree-0.0.1
Parsing documentation for binarytree-0.0.1
Installing ri documentation for binarytree-0.0.1
Done installing documentation for binarytree after 0 seconds
Done installing documentation for binarytree (0 sec).
1 gem installed

4)然后启动irb并需要新的gem:

irb(main):001:0> require 'binarytree'