require और require_relative
require एक library से code लाता है, और require_relative आपकी file के बगल वाली एक file लाता है। यह public library से एक book उधार लेने बनाम अपनी shelf से लेने जैसा है।
In this page:
Syntax
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
require "json"
data = { name: "Alice", age: 30 }
json_text = data.to_json
puts json_text
puts JSON.parse(json_text).inspect
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- एक अलग working directory में एक relative path के साथ
require "./helper"इस्तेमाल करना, जबrequire_relative "helper"safer है। to_jsonयाJSON.parsecall करने से पहलेrequire "json"भूल जाना, जोNoMethodErrorयाNameErrorraise करता है।- same file को कई बार require करना और इसके reload होने की उम्मीद करना, जब
requireएक file सिर्फ एक बार load करता है।
चैप्टर सारांश
- Modules methods और constants group करते हैं, और
includeऔरextendइन्हें classes में mix करते हैं। ComparableऔरEnumerablecomparison और collection behavior add करते हैं।- Namespacing,
require, औरrequire_relativecode organize और load करते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: