Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/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,具有以下文件: # ./app.rb require_relative 'container' require_relative 'contained' # ./container.rb class Foo def initialize &block puts block.call end end # ./contained.rb Foo.new do "Hello, world!" end 我们可以从控制台测试并查看一切是否正常: $ ruby ./app.r

具有以下文件:

# ./app.rb
require_relative 'container'
require_relative 'contained'

# ./container.rb
class Foo
  def initialize &block
    puts block.call
  end
end

# ./contained.rb
Foo.new do
  "Hello, world!"
end
我们可以从控制台测试并查看一切是否正常:

$ ruby ./app.rb
Hello, world!
但是我想通过删除
Foo.new do
end
来简化contained.rb,通过修改app.rb只保留块的内容

在这次探索中,我得到了以下结果:

# ./app.rb
require_relative 'container'
require_relative 'contained'

Foo.new do
  eval File.open('contained.rb').read
end

# ./container.rb
class Foo
  def initialize &block
    puts block.call
  end
end

# ./contained.rb
"Hello, world!"
同样的结果是:

$ ruby ./app.rb
Hello, world!
然而,我对这段代码不是很自豪,主要是因为
eval
方法。在这种情况下有没有最佳做法?你会怎么做?
感谢分享您的想法。

您希望从单独的文件中读取的事实必须是您希望将其与主代码分开,并且您希望偶尔对其进行更改。这类东西属于所谓的配置。现在,将其作为YAML文件编写并使用YAML库读入Ruby是很常见的。

我将在第一个示例中保留它。第二,除了使用eval外,还为代码引入了一些魔力,可能会让您或其他开发人员在几周/几个月/几年内挠头。是什么帮助您决定使用eval?我同意。这不值得努力。保留第一个示例中的代码更明智。谢谢你,@a-fader-darkly。谢谢你的回答,@sawa!我现在看得更清楚了。