Câu hỏi phỏng vấn Ruby
Câu hỏi

What is the difference between Kernel#require and Kernel#load ?

Câu trả lời

In Ruby, both Kernel#require and Kernel#load are methods used to include external files into a Ruby program, but they serve slightly different purposes and behave in distinct ways.

Kernel#require

Kernel#require is used to load and parse Ruby files only once. When a file is required, Ruby marks it as loaded and will not load it again if another require statement with the same filename is encountered. This is particularly useful for libraries or dependencies, ensuring that the file is only executed once, avoiding potential redefinition of constants, methods, or classes which could lead to unexpected behavior.

  • Idempotence: Once a file has been required, subsequent require calls for that file will have no effect.
  • File Extensions: require can load .rb files or binary extensions such as .so, .o, or .dll files. If the file extension is omitted, require will attempt to match it with any of the supported extensions.
  • Load Path: require searches for files in the directories listed in $LOAD_PATH ($:). If the filename does not represent an absolute path, require searches in $LOAD_PATH.
  • Return Value: Returns true if the file is loaded for the first time, and false if it has already been loaded.

Kernel#load

Kernel#load, on the other hand, is used to read and parse files every time it is called, regardless of whether it has been loaded before. This method is typically used for loading configuration files or other types of data that might change during the program's execution and need to be reloaded.

  • Non-idempotent: load will reload and reparse a file each time it is called, which can be useful for dynamic file content that needs to be updated frequently.
  • File Extensions: load requires the complete filename including its extension. It primarily handles .rb files.
  • Load Path: Unlike require, load does not search $LOAD_PATH for the file unless the filename is an absolute path. Typically, the relative pat...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Describe a closure in Ruby

entry

What is the highest level in the object model?

senior

What is the difference between Object#dup and #clone ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào