Block के साथ File.open
एक block के साथ File.open एक file खोलता है, आपको इसके साथ काम करने देता है, और खत्म होने पर automatically close कर देता है। यह एक door की तरह है जो आपके पीछे खुद बंद हो जाता है।
In this page:
Syntax
File.open("path", "mode") do |file|
file.puts "text"
end
Block के साथ File.open
File.open("path", "mode") { |file| ... } एक file खोलता है और block खत्म होते ही automatically इसे close कर देता है, भले ही अंदर एक error हो -- manual cleanup की ज़रूरत से बचते हुए।
"r" (read), "w" (write), और "a" (append) जैसी Mode strings control करती हैं कि file कैसे open होती है। यह block form Ruby में files के साथ काम करने का idiomatic, safe तरीका है।
Note:
हमेशा File.open का block form prefer करें -- यह guarantee करता है कि file automatically close होती है, भले ही एक exception raise हो।
उदाहरण: File.open with a Block
File.open("notes.txt", "w") do |file|
file.puts "Line one"
file.puts "Line two"
end
File.open("notes.txt", "r") do |file|
file.each_line { |line| puts line.chomp }
end
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. #}
आम गलतियां
- एक file पर
"w"mode इस्तेमाल करना जिसका content रहना चाहिए, जो इसे erase कर देता है; append के लिए"a"इस्तेमाल करें। - बिना block के
File.openइस्तेमाल करना औरfile.closeभूल जाना, इसे open छोड़ते हुए। "w"mode से पढ़ना या"r"mode से लिखना, जोIOErrorraise करता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: