简体   繁体   中英

Ruby - how to reload a file with changes in IRB or 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, eg

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

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

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 (ie, calling methods or instatiating objects yourself) but can become a bit hairy if one of the "big guns" aka 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 load s in the irb sometimes seemingly having no effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM