将文件加载到rails控制台,并访问该文件中定义的变量

时间:2021-12-23 23:05:38

I work with rails console and often i need to preload some ruby code to work with.

我使用rails控制台,经常需要预加载一些ruby代码。

#file that i want to load in rails console
#my_file.rb
a = 1
b = 2
puts a + b 

When i run my console with ./script/console

当我使用。/脚本/控制台运行控制台时

rails-console :001 > load 'my_file.rb' 
3
 => []
rails-console :002 > a
NameError: undefined local variable or method 'a' for #<Object:123445>

How can i get access to my 'a' and 'b' variables in console?

如何访问控制台中的“a”和“b”变量?

2 个解决方案

#1


16  

When you load a file local variables go out of scope after the file is loaded that is why a and b will be unavailable in the console that loads it.

当加载文件时,本地变量在加载文件后超出范围,这就是为什么加载文件的控制台中a和b不可用的原因。

Since you are treating a and b as constants how about just capitalizing them like so

既然你把a和b看做常数那么把它们资本化

A = 1
B = 2
puts A+B

Now in you console you should be able to do the following

现在在您的控制台中,您应该能够执行以下操作

load 'myfile.rb'
A #=> 1

Alternately you could make the variables in myfile.rb global ($a, $b)

或者,您可以在myfile中创建变量。rb全球(a,b)美元

#2


0  

First of all, you should use an irbrc. Please read more here for example.

首先,您应该使用irbrc。请在这里阅读更多的例子。

Then you could define a method in your irbrc to mock your variables:

然后你可以在irbrc中定义一个方法来模拟你的变量:

def a
 [1, 2, 4]
end

but I prefer to add methods to specific Ruby classes like:

但是我更喜欢为特定的Ruby类添加方法,比如:

class Array
  def self.toy(n=10,&block)
    block_given? ? Array.new(n,&block) : Array.new(n) {|i| i+1}
  end
end 

#1


16  

When you load a file local variables go out of scope after the file is loaded that is why a and b will be unavailable in the console that loads it.

当加载文件时,本地变量在加载文件后超出范围,这就是为什么加载文件的控制台中a和b不可用的原因。

Since you are treating a and b as constants how about just capitalizing them like so

既然你把a和b看做常数那么把它们资本化

A = 1
B = 2
puts A+B

Now in you console you should be able to do the following

现在在您的控制台中,您应该能够执行以下操作

load 'myfile.rb'
A #=> 1

Alternately you could make the variables in myfile.rb global ($a, $b)

或者,您可以在myfile中创建变量。rb全球(a,b)美元

#2


0  

First of all, you should use an irbrc. Please read more here for example.

首先,您应该使用irbrc。请在这里阅读更多的例子。

Then you could define a method in your irbrc to mock your variables:

然后你可以在irbrc中定义一个方法来模拟你的变量:

def a
 [1, 2, 4]
end

but I prefer to add methods to specific Ruby classes like:

但是我更喜欢为特定的Ruby类添加方法,比如:

class Array
  def self.toy(n=10,&block)
    block_given? ? Array.new(n,&block) : Array.new(n) {|i| i+1}
  end
end