简体   繁体   English

如何将局部变量从模块导入到 Ruby 中的另一个类

[英]How to import local variable from a module to another class in Ruby

I am new in Ruby.我是 Ruby 新手。

I have a situation where I am generating some values at runtime in a module and I need to access it in another class.我有一种情况,我在运行时在一个模块中生成一些值,我需要在另一个类中访问它。 What is the best way to do it?最好的方法是什么? Below I have given my directory structure and a dummy code.下面我给出了我的目录结构和一个虚拟代码。 I want to import "local_variable_a" from module.rb into someclass.rb.我想将“local_variable_a”从module.rb 导入someclass.rb。

Directory Structure :目录结构:

Folder_A -> Folder_B -> Folder_C -> module.rb Folder_A -> Folder_B -> Folder_C -> module.rb

Folder_A -> Folder_D -> someclass.rb Folder_A -> Folder_D -> someclass.rb

module.rb模块.rb

Module First
  Module Second
    def some_method
      local_variable_a = some_value
    end
  end
end    

someclass.rb某个类.rb

class Example
  def initialize(example)
    @example = example
  end

  def another_method
    local_variable_a = some_value  //import from module.rb
  end

Local variables in Ruby are just that. Ruby 中的局部变量就是这样。 They are lexical variables that exist in the lexical scope (method, block, etc) where they are defined.它们是存在于定义它们的词法范围(方法、块等)中的词法变量。 As soon as that scope closes off they are garbage collected.一旦该范围关闭,它们就会被垃圾收集。

For example assigning the local variable here is completely pointless as its garbage collected as soon as the method finsishes:例如,在这里分配局部变量是完全没有意义的,因为一旦方法完成,它的垃圾就会被收集:

def another_method
  local_variable_a = some_value  //import from module.rb
end

There is no variable importing feature in Ruby as its based around the use of methods for message passing. Ruby 中没有变量导入功能,因为它基于使用消息传递方法。 To "import" variables you pass them as input to methods - to "export" variables you return them from a method.要“导入”变量,您将它们作为输入传递给方法 - 要“导出”变量,您可以从方法中返回它们。

If you want a module to expose anything you would do it through a method:如果你想让一个模块暴露任何东西,你可以通过一个方法来做:

module Foo
   # this is an instance variable that belongs to the module
  @baz = "Hello World"
  def self.bar
    @baz
  end
end

puts Foo.bar

If you want to have a module define a set of instance variables then just create an instance method that you call from your initializer:如果你想让一个模块定义一组实例变量,那么只需创建一个从初始化程序调用的实例方法:

module TimeStamps
  def set_timestamps!
    @initialized_at = Time.now
  end

  def initialized_at 
    @initialized_at
  end
end

class Bar
  include TimeStamps

  def initialize
    # ...
    set_timestamps!
  end
end

Bar.new.initialized_at
# => 2021-06-18 12:44:32.357627871 +0200

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM