Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 从模块内访问变量_Ruby_Oop - Fatal编程技术网

Ruby 从模块内访问变量

Ruby 从模块内访问变量,ruby,oop,Ruby,Oop,试图从模块内部获取在模块外部定义的变量 @variable = "variable" module A def write puts @variable end end extend A write # -> "variable" # works ok, but i'll be loading a few modules with the same method name "write" # need to be able to call A.write, A1.wri

试图从模块内部获取在模块外部定义的变量

@variable = "variable"

module A
  def write
    puts @variable
  end
end

extend A
write # -> "variable"
# works ok, but i'll be loading a few modules with the same method name "write"
# need to be able to call A.write, A1.write, A2.write and so on

module B
  module_function
  def write
    puts @variable
  end
end

extend B
B.write # ->  
# Can call the B.write
# is returning nothing, not getting @variable

module C
  module_function
  def write var
    puts var
  end
end

extend C
C.write @variable # -> "variable"
# works ok

我在实践中发现的解决方案好吗?还是有更好的方法?我不确定是否调用module_函数,因为在阅读了定义之后我仍然没有得到它,不确定它还做了什么

这听起来不太明智。请解释你试图用这种方法解决的问题。
A.write(@variable)
等有什么问题?在模块外定义变量的原因是什么?您可以尝试
@@variable
它可以通过常规方法访问(在这方面,它们更类似于Java的静态字段)。我正在尝试制作一个ruby可执行文件,用于搭建我的开发环境,纯粹是为了学习。简而言之,我想用write方法创建ruby模块,如“Bower.rb”、“Grunt.rb”,该方法包含我喜欢的特定实用程序的设置
A.write@variable
返回错误,因为它不需要argument@hawk我想设置一个项目名称var
@project\u name
,并让我的模块根据正确设置的项目名称设置我的实用程序。我记得github上的ruby风格指南repo告诉我远离
@
vars,因为它的继承行为,但我会尝试它,因为它给了我一个统一的类变量错误。我猜是因为模块函数语句?