← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 6 of 6

require और require_relative

require एक library से code लाता है, और require_relative आपकी file के बगल वाली एक file लाता है। यह public library से एक book उधार लेने बनाम अपनी shelf से लेने जैसा है।
Syntax
ruby
require "library"
require_relative "path/to/file"

require और require_relative

require "library" Ruby की standard library या एक installed gem से code load करता है, जबकि require_relative "./file" current file की location के relative एक file load करता है, आमतौर पर आपके अपने project की files के लिए इस्तेमाल होता है।

दोनों एक दी गई file सिर्फ एक बार load करते हैं, भले ही कई बार require हो, duplicate definitions avoid करते हुए। यह कई files में code split करने और external libraries reuse करने का Ruby का mechanism है।

Note: अपने project files के लिए require_relative इस्तेमाल करें और standard library या installed gems के लिए require।

उदाहरण: require and require_relative

markup
require "json"

data = { name: "Alice", age: 30 }
json_text = data.to_json

puts json_text
puts JSON.parse(json_text).inspect
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक अलग working directory में एक relative path के साथ require "./helper" इस्तेमाल करना, जब require_relative "helper" safer है।
  2. to_json या JSON.parse call करने से पहले require "json" भूल जाना, जो NoMethodError या NameError raise करता है।
  3. same file को कई बार require करना और इसके reload होने की उम्मीद करना, जब require एक file सिर्फ एक बार load करता है।
चैप्टर सारांश
  • Modules methods और constants group करते हैं, और include और extend इन्हें classes में mix करते हैं।
  • Comparable और Enumerable comparison और collection behavior add करते हैं।
  • Namespacing, require, और require_relative code organize और load करते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.