Rubyで別ファイルのトップレベルの変数を使う方法
Rubyで別ファイルのトップレベルの変数を使いたい
とあるスクリプト(a.rb)がありまして、変数がひとつaというものがあります。
$ cat a.rb a="Newcastle"
その変数aを別ファイル(test.rb)から呼び出したかったのですが、うまくできなかったのです。
requireならエラー
$ cat test.rb require "a.rb" p a
$ irb test.rb test.rb(main):001:0> require "a.rb" => true test.rb(main):002:0> p a NameError: undefined local variable or method `a' for main:Object from test.rb:2
loadでもエラー
$ cat test.rb load "a.rb" p a
$ irb test.rb test.rb(main):001:0> load "a.rb" => true test.rb(main):002:0> p a NameError: undefined local variable or method `a' for main:Object from test.rb:2
どうしてもやりたかったので
無理やりやればいけました
$ cat test.rb eval File.read "a.rb" p a
$ irb test.rb test.rb(main):001:0> eval File.read "a.rb" => "Newcastle" test.rb(main):002:0> p a "Newcastle" => nil
ちなみにperlだとrequireで動きました。