Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - how to reload a file with changes in IRB or PRY?

Tags:

ruby

irb

pry

I go into irb and require a file

irb> require_relative 'prime'
irb> true

This file contains the following code:

def is_prime? num
  (2..num-1).each do |div_by|
    if num % div_by == 0
      return false
    end 
  end 
  true
end

requiring the file in irb works and I can use the method, e.g.

irb> require_relative 'prime'
irb> is_prime? 10
irb> -> false

irb> is_prime? 11
irb> -> true

However if I modify the source file, say add puts 'HHH', that does not show up unless I exit the console and re-enter and then require the file

If I stay in the console and require the file again I get false as it is already loaded and I don't get the new changes

I have tried

irb> reload

and

irb> reload!

but they give me

NoMethodError (undefined method `reload!' for main:Object)

Also I tried

irb> load 'prime.rb'
irb> => true

but did not pick up the change

Using PRY gave similar results

like image 962
Michael Durrant Avatar asked May 13 '19 12:05

Michael Durrant


2 Answers

Try Kernel#load with relative path to rb file:

irb> load './path/to/prime.rb'

Kernel#require loads a source file only once, while Kernel#load loads it every time you call it.

Ref https://stackoverflow.com/a/4633535/4950680

like image 110
Martin Zinovsky Avatar answered Sep 24 '22 05:09

Martin Zinovsky


require just says that you literally "require" some other .rb file to be loaded. Once it is loaded, that requirement is satisfied, and further require calls with the same target file are ignored. This makes it save to have the same require call sprinkled liberately across many source files - they won't actually do anything after the first one has been executed.

You can use load to force it to actually load the file - this should do exactly what you expect (require calls load after checking whether the file has already been required).

Note that all of this is straightforward if you are in a plain-old-ruby context (i.e., calling methods or instatiating objects yourself) but can become a bit hairy if one of the "big guns" a.k.a. Rails is involved. Rails does a lot of magic behind the scenes to automatically require missing stuff (hence why you see so few explicit require calls in Rails code) - which leads to explicit loads in the irb sometimes seemingly having no effect.

like image 23
AnoE Avatar answered Sep 22 '22 05:09

AnoE