【问题标题】:Three Ruby classes, more than three problems?三个 Ruby 类,不止三个问题?
【发布时间】:2014-04-26 14:55:34
【问题描述】:

我在同一个目录中有三个 Ruby 文件:

classthree.rb
otherclass.rb
samplecode.rb

这里是classthree.rb的内容:

require './samplecode.rb'
require './otherclass.rb'

class ClassThree

  def initialize()
    puts "this class three here"
  end

end

这里是samplecode.rb的内容:

require './otherclass.rb'
require './classthree.rb'

class SampleCode

  $smart = SampleCode.new
  @sides = 3
  @@x = "333"

  def ugly()
    g = ClassThree.new
    puts g
    puts "monkey see"
  end


  def self.ugly()
    s = SampleCode.new
    s.ugly
    puts s
    puts $smart
    puts "monkey see this self"
  end

  SampleCode.ugly

end

这是otherclass.rb的内容:

require './samplecode.rb'
require './classthree.rb'

END {
  puts "ending"
}

BEGIN{
  puts "beginning"
}

class OtherClass

  def initialize()
    s = SampleCode.new
    s.ugly
  end

end

我的两个问题是:

  1. 对于目录中的每个类,都必须有比require './xyz.rb' 更好的方法。没有类似 require './*.rb' 的东西吗?
  2. 当我运行 ruby otherclass.rb 时,我得到以下输出:

为什么我会得到两次“开始”和“结束”??

【问题讨论】:

  • 从您的代码中提取与您的观点无关的任何内容。显示表明您的观点所需的最低要求。
  • 考虑将您的项目转换为 Ruby gem。 Rubygems 是 Ruby 的一个模块系统,它通过管理库搜索路径来工作。永远不需要在$LOAD_PATH 周围进行黑客攻击。
  • 另见this问题。

标签: ruby


【解决方案1】:

在 1 - 处理它的最佳方法是创建另一个文件。你可以称它为environment.rbinitialize.rb,它需要所有需要的文件。

$LOAD_PATH.unshift File.dirname(__FILE__)

require 'samplecode.rb'
require 'classthree.rb'
require 'classthree.rb'

现在您只需在应用程序启动时要求此文件一次。

在 2 - 您从文件“otherclass.rb”开始。它显示第一个“开始”位,然后加载samplecode.rb 文件。此时,“otherclass.rb”尚未加载——任何其他文件都不需要它。因此samplecode.rb 正在重新运行整个otherclass.rb,这是需要的。重新运行不会重新加载“samplecode.rb”,因为它已经被需要(需要首先检查文件是否需要)。这就是您看到这些消息两次的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    相关资源
    最近更新 更多