Michael Durrant
Michael Durrant

Reputation: 96594

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

I want to reload a file in irb. The file, prime.rb, 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

I can use require_relative to require the file:

irb(main):001> require_relative 'prime'
=> true
irb(main):002> is_prime? 10
=> false
irb(main):003> is_prime? 11
=> true

If I make a change to prime.rb, how can I reload the file? I have tried:

irb(main):004> require_relative 'prime'
=> false

The same behavior occurs in pry.

Upvotes: 6

Views: 5427

Answers (3)

Using PRY:

In my case, load was returning true and with $ MyClass.method I could see the new source code, yet the method was still performing old code.

I solved by using reset command (pry only) as suggested here

Upvotes: 1

AnoE
AnoE

Reputation: 8355

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.

Upvotes: 3

Martin
Martin

Reputation: 4222

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

Upvotes: 12

Related Questions