如何从Ruby中的另一个实例访问全局实例变量

时间:2014-02-03 22:15:36

标签: ruby variables

我是Ruby新手,我正在尝试使用当前框架更改我的一些代码以进行OO设计。将我的实用程序文件转换为类时遇到以下问题:

有两个函数* create_output_file *和* write_to *是我无法触及的框架方法(不属于任何类)(它们指定写入框架的位置)。
还有一个我编写的A类需要使用* write_to *来记录 foo()的时间和返回状态。

<!-- language: lang-rb -->
def create_output_file(params)
  @output_file = params["SS_output_file"]
  @hand = File.open(@output_file, "a")
  write_to "New Run - Shell Cmd\n\n"
  return true
end
def write_to(message, newline = true)
  return if message.nil?
  sep = newline ? "\n" : ""
  @hand.print(message + sep)
  print(message + sep)
end

def this_is_dum
  print("This is to show class A have access to global methods.\n")
end

class A
  def foo()
    # Do something that needs the status of instance A
    this_is_dum()
    write_to("This is the current status!")
  end

end

# Main routine
params = {}
params["SS_output_file"] = "./debugging_log"
create_output_file(params)  #sets the @hand file handle
A.new.foo

这些是我得到的输出:

  

New Run - Shell Cmd:

     

这表明A类可以访问全局方法。   D:/data/weshi/workspace/RubyBRPM2/scripts/Random.rb:12:在`write_to'中:   私有方法`print'调用nil:NilClass(NoMethodError)
    来自D:/data/weshi/workspace/RubyBRPM2/scripts/Random.rb:18:in:   `foo'来自   d:/data/weshi/workspace/RubyBRPM2/scripts/Random.rb:26:在   `'

经过挖掘后,我发现在@hand范围内未访问foo()
我不确定如何在不分配类的情况下访问A类中的@hand变量及其含义。但我确实需要write_to函数才能按照整个框架工作。任何建议或指示都受到欢迎和赞赏。

1 个答案:

答案 0 :(得分:0)

您可以在构造函数中将@hand提供给A实例:

def create_output_file(params)
  @output_file = params["SS_output_file"]
  @hand = File.open(@output_file, "a")
  write_to "New Run - Shell Cmd\n\n"
  return true
end
def write_to(message, newline = true)
  return if message.nil?
  sep = newline ? "\n" : ""
  @hand.print(message + sep)
  print(message + sep)
end

def this_is_dum
  print("This is to show class A have access to global methods.\n")
end

class A
  def initialize(hand)
    @hand = hand
  end

  def foo()
    # Do something that needs the status of instance A
    this_is_dum()
    write_to("This is the current status!")
  end

end

# Main routine
params = {}
params["SS_output_file"] = "./debugging_log"
create_output_file(params)  #sets the @hand file handle
A.new(@hand).foo

输出结果为:

New Run - Shell Cmd

This is to show class A have access to global methods.
This is the current status!

否则我发现that可能会有点复杂。