I work with rails console and often i need to preload some ruby code to work with.
#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?
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.
Since you are treating a and b as constants how about just capitalizing them like so
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)
First of all, you should use an irbrc. Please read more here for example.
Then you could define a method in your irbrc to mock your variables:
def a
[1, 2, 4]
end
but I prefer to add methods to specific Ruby classes like:
class Array
def self.toy(n=10,&block)
block_given? ? Array.new(n,&block) : Array.new(n) {|i| i+1}
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With