← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 2 of 6

Block के साथ File.open

एक block के साथ File.open एक file खोलता है, आपको इसके साथ काम करने देता है, और खत्म होने पर automatically close कर देता है। यह एक door की तरह है जो आपके पीछे खुद बंद हो जाता है।
Syntax
ruby
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

markup
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
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. एक file पर "w" mode इस्तेमाल करना जिसका content रहना चाहिए, जो इसे erase कर देता है; append के लिए "a" इस्तेमाल करें।
  2. बिना block के File.open इस्तेमाल करना और file.close भूल जाना, इसे open छोड़ते हुए।
  3. "w" mode से पढ़ना या "r" mode से लिखना, जो IOError raise करता है।
🔒

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.