{"id":40839,"date":"2026-01-06T14:24:44","date_gmt":"2026-01-06T14:24:44","guid":{"rendered":"https:\/\/www.railscarma.com\/?p=40839"},"modified":"2026-01-06T14:24:47","modified_gmt":"2026-01-06T14:24:47","slug":"how-to-read-and-write-files-in-ruby-with-examples","status":"publish","type":"post","link":"https:\/\/www.railscarma.com\/it\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/","title":{"rendered":"How To Read and Write Files in Ruby (With Examples)"},"content":{"rendered":"<div data-elementor-type=\"wp-post\" data-elementor-id=\"40839\" class=\"elementor elementor-40839\" data-elementor-post-type=\"post\">\n\t\t\t\t\t\t<section class=\"elementor-section elementor-top-section elementor-element elementor-element-fb4f7f3 elementor-section-boxed elementor-section-height-default elementor-section-height-default\" data-id=\"fb4f7f3\" data-element_type=\"section\">\n\t\t\t\t\t\t<div class=\"elementor-container elementor-column-gap-default\">\n\t\t\t\t\t<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-96e3d48\" data-id=\"96e3d48\" data-element_type=\"column\">\n\t\t\t<div class=\"elementor-widget-wrap elementor-element-populated\">\n\t\t\t\t\t\t<div class=\"elementor-element elementor-element-3d3c3ad elementor-widget elementor-widget-text-editor\" data-id=\"3d3c3ad\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t\t\t\t\t<p>Ruby provides simple, elegant, and powerful ways to read from and write to files. The language emphasizes readability and developer happiness, making file I\/O operations straightforward. This guide covers the most common and idiomatic approaches with practical examples.<\/p><h3><strong>Basic Concepts<\/strong><\/h3><p>In Ruby, file operations are typically performed using the <code>File<\/code> class or the shorter <code>File.open<\/code> method. Most file operations use <strong>blocks<\/strong> to ensure files are properly closed after use, preventing resource leaks.<\/p><h3><strong>Opening a File<\/strong><\/h3><p>The recommended way is to use a block form:<\/p><pre>ruby\nFile.open(\"filename.txt\", \"r\") do |file|\n  <em># work with the file<\/em>\nFINE\n<em># file is automatically closed here<\/em><\/pre><p>Without a block, you must manually close the file:<\/p><pre>ruby\nfile = File.open(\"filename.txt\", \"r\")\n<em># ... operations ...<\/em>\nfile.close<\/pre><h3><strong>File Modes<\/strong><\/h3><p>The second argument to <code>File.open<\/code> is the <strong>mode<\/strong> string:<\/p><table width=\"624\"><tbody><tr><td width=\"102\"><strong>Mode<\/strong><\/td><td width=\"522\"><strong>Meaning<\/strong><\/td><\/tr><tr><td width=\"102\">&#8220;r&#8221;<\/td><td width=\"522\">Read-only (default)<\/td><\/tr><tr><td width=\"102\">&#8220;w&#8221;<\/td><td width=\"522\">Write-only, creates\/truncates file<\/td><\/tr><tr><td width=\"102\">&#8220;a&#8221;<\/td><td width=\"522\">Write-only, appends to file<\/td><\/tr><tr><td width=\"102\">&#8220;r+&#8221;<\/td><td width=\"522\">Read and write, preserves content<\/td><\/tr><tr><td width=\"102\">&#8220;w+&#8221;<\/td><td width=\"522\">Read and write, truncates file<\/td><\/tr><tr><td width=\"102\">&#8220;a+&#8221;<\/td><td width=\"522\">Read and write, appends<\/td><\/tr><\/tbody><\/table><p>Add &#8220;b&#8221; for binary mode on Windows (e.g., &#8220;rb&#8221;, &#8220;wb&#8221;).<\/p><h3><strong>Reading Files in Ruby<\/strong><\/h3><p><strong>1. Read Entire File as a String<\/strong><\/p><pre>ruby\ncontent = File.read(\"example.txt\")\nputs content<\/pre><p>Or using <code>File.open<\/code>:<\/p><pre>ruby\ncontent = File.open(\"example.txt\", \"r\") { |f| f.read }<\/pre><p><strong>2. Read Entire File into an Array of Lines<\/strong><\/p><pre>ruby\nlines = File.readlines(\"example.txt\")\nlines.each { |line| puts line }\n\n<em># Or more idiomatically:<\/em>\nFile.readlines(\"example.txt\").each do |line|\n  puts \"Line: #{line.chomp}\"\nend<\/pre><p><strong>3.<\/strong> <strong>Read Line by Line (Most Memory-Efficient)<\/strong><\/p><p>Ideal for large files:<\/p><pre>ruby\nFile.open(\"large_file.txt\", \"r\") do |file|\n  file.each_line do |line|\n \u00a0\u00a0 puts line.chomp.upcase\n  end\nend<\/pre><p>Or using the shorter <code>foreach<\/code>:<\/p><pre>ruby\nFile.foreach(\"large_file.txt\") do |line|\n  process(line.chomp)\nend<\/pre><p><strong>4. Read Specific Number of Bytes or Lines<\/strong><\/p><pre>ruby\nFile.open(\"data.bin\", \"rb\") do |f|\n  header = f.read(16)\u00a0\u00a0\u00a0\u00a0\u00a0 <em># read first 16 bytes<\/em>\n  puts header\nend\n\n<em># Read first 5 lines<\/em>\nfirst_five = File.foreach(\"log.txt\").first(5)<\/pre><p><strong>5. Read with Encoding Specified<\/strong><\/p><pre>ruby\ncontent = File.read(\"utf8_file.txt\", encoding: \"UTF-8\")\n<em># or<\/em>\nFile.open(\"file.txt\", \"r:UTF-8\") do |f|\n  f.each_line { |line| puts line }\nend<\/pre><h3><strong>Writing Files in Ruby<\/strong><\/h3><p><strong>1. Write a String to a File (Overwrites)<\/strong><\/p><pre>ruby\nFile.write(\"output.txt\", \"Hello, Ruby!\\nThis is a new file.\")<\/pre><p>This is the simplest and most common way.<\/p><p><strong style=\"font-size: 16px;\">2. Write Using File.open (Block Form)<\/strong><\/p><pre>ruby\nFile.open(\"greeting.txt\", \"w\") do |file|\n  file.puts \"Hello World\"\n  file.puts \"Welcome to Ruby file I\/O\"\n  file.write \"This line is written without newline\"\n  file &lt;&lt; \" &lt;&lt; This uses the shovel operator\\n\"\nend<\/pre><p>Methods available inside the block:<\/p><ul><li><code>puts<\/code> \u2013 adds newline<\/li><li><code>print<\/code> \u2013 no newline<\/li><li><code>write<\/code> \u2013 no newline (alias for <code>&lt;&lt;<\/code>)<\/li><li><code>&lt;&lt;<\/code> \u2013 shovel operator<\/li><\/ul><p><strong style=\"font-size: 16px;\">3. Append to a\u00a0 File<\/strong><\/p><pre>ruby\nFile.open(\"log.txt\", \"a\") do |file|\n  file.puts \"#{Time.now}: Application started\"\nend\n\n<em># Or shorter:<\/em>\nFile.write(\"log.txt\", \"New log entry\\n\", mode: \"a\")<\/pre><p><strong style=\"font-size: 16px;\">4. Write Array of Lines<\/strong><\/p><pre>ruby\nlines = [\"First line\", \"Second line\", \"Third line\"]\n\nFile.open(\"lines.txt\", \"w\") do |file|\n  lines.each { |line| file.puts line }\nend\n\n<em># Or even shorter:<\/em>\nFile.write(\"lines.txt\", lines.join(\"\\n\") + \"\\n\")<\/pre><h3><strong>Practical Examples<\/strong><\/h3><h5><strong>Example 1: Copy a File<\/strong><\/h5><pre>ruby\ndef copy_file(source, destination)\n  File.write(destination, File.read(source))\nend\n\ncopy_file(\"source.txt\", \"backup.txt\")<\/pre><p>Or in binary mode:<\/p><pre>ruby\nFile.write(\"backup.bin\", File.read(\"original.bin\", mode: \"rb\"), mode: \"wb\")<\/pre><h5><strong>Example 2: Simple CSV Writer<\/strong><\/h5><pre>ruby\ndata = [\n  [\"Name\", \"Age\", \"City\"],\n  [\"Alice\", 30, \"New York\"],\n  [\"Bob\", 25, \"London\"]\n]\n\nFile.open(\"people.csv\", \"w\") do |file|\n  data.each do |row|\n \u00a0\u00a0 file.puts row.join(\",\")\n  end\nend<\/pre><h5><strong>Example 3: Simple CSV Reader<\/strong><\/h5><pre>ruby\nFile.foreach(\"people.csv\") do |line|\n  name, age, city = line.chomp.split(\",\")\n  puts \"#{name} is #{age} years old and lives in #{city}\"\nend<\/pre><h5><strong>Example 4: Count Lines in a File<\/strong><\/h5><pre>ruby\nline_count = File.foreach(\"large.txt\").inject(0) { |count, _| count + 1 }\nputs \"Total lines: #{line_count}\"\n\n<em># Or more simply (loads all lines into memory):<\/em>\nputs File.readlines(\"file.txt\").size<\/pre><h5><strong>Example 5: Safe File Writing (Atomic Write)<\/strong><\/h5><p>To avoid corrupted files on crash, write to temporary file first:<\/p><pre>ruby\nrequire 'tempfile'\n\nTempfile.create('safe_write') do |temp_file|\n  temp_file.puts \"Important data\"\n  temp_file.puts \"More important data\"\n  temp_file.flush\n\n  <em># Now atomically replace the target file<\/em>\n  File.rename(temp_file.path, \"important.txt\")\nend<\/pre><h3><strong>Working with Paths<\/strong><\/h3><p>Utilizzo <code>File.expand_path, File.join<\/code>, E <code>Pathname<\/code> for robust path handling:<\/p><pre>ruby\nrequire 'pathname'\n\npath = Pathname.new(\"\/tmp\") \/ \"myapp\" \/ \"log.txt\"\nFile.write(path, \"Log entry\")\n\n<em># Or using File.join<\/em>\nfull_path = File.join(Dir.home, \"Documents\", \"notes.txt\")<\/pre><h3><strong>Error Handling<\/strong><\/h3><p>Always handle potential errors:<\/p><pre>ruby\nbegin\n  content = File.read(\"nonexistent.txt\")\nrescue Errno::ENOENT\n  puts \"File not found!\"\nrescue Errno::EACCES\n  puts \"Permission denied!\"\nrescue =&gt; e\n  puts \"Error: #{e.message}\"\nend<\/pre><p>Or more idiomatically:<\/p><pre>ruby\nif File.exist?(\"config.txt\")\n  config = File.read(\"config.txt\")\nelse\n  puts \"Config file missing, using defaults\"\nend<\/pre><h3><strong>Best Practices to Read and Write Files in Ruby<\/strong><\/h3><ol><li><strong>Always use block form<\/strong> when possible \u2013 ensures file closure.<\/li><li><strong>Utilizzo <\/strong><code>File.read<strong>\/<\/strong>File.write<\/code> for simple whole-file operations.<\/li><li><strong>Utilizzo <\/strong><code>foreach<\/code> for large files to avoid loading everything into memory.<\/li><li><strong>Specify encoding<\/strong> when working with non-ASCII text.<\/li><li><strong>Check file existence<\/strong> before reading if needed.<\/li><li><strong>Use appropriate modes<\/strong> (especially binary mode on Windows).<\/li><li><strong>Handle exceptions<\/strong> gracefully in production code.<\/li><\/ol><h2><strong>Conclusione<\/strong><\/h2><p>A <a href=\"https:\/\/www.railscarma.com\/it\"><strong>RailsCarma<\/strong><\/a>, un'azienda leader <a href=\"https:\/\/www.railscarma.com\/it\"><strong>Societ\u00e0 di sviluppo Ruby on Rails<\/strong><\/a>, our expert developers leverage Ruby\u2019s elegant file I\/O capabilities to deliver robust and maintainable applications. Ruby\u2019s clean syntax, block-based resource management, and powerful methods like <code>File.read<\/code> E <code>File.write<\/code> make <strong>file handling in Ruby<\/strong> safe, efficient, and scalable.<\/p><p>Whether it\u2019s processing configuration files, managing logs, generating reports, or building complex data pipelines, our <a href=\"https:\/\/www.railscarma.com\/it\"><strong>Servizi di sviluppo delle rotaie<\/strong><\/a> ensure minimal boilerplate, maximum expressiveness, and high performance. By choosing to <a href=\"https:\/\/www.railscarma.com\/it\/assumere-ruby-on-rails-sviluppatore\/\"><strong>hire Ruby developers<\/strong><\/a> from RailsCarma, you gain access to skilled engineers who build reliable, high-quality Rails applications tailored to your business needs.<\/p>\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/section>\n\t\t\t\t<\/div>\n\t\t  <div class=\"related-post slider\">\r\n        <div class=\"headline\">Articoli correlati<\/div>\r\n    <div class=\"post-list owl-carousel\">\r\n\r\n            <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\"Building Agentic AI Applications with Ruby on Rails\" href=\"https:\/\/www.railscarma.com\/it\/blog\/building-agentic-ai-applications-with-ruby-on-rails\/?related_post_from=41339\">\r\n\r\n      <img decoding=\"async\" width=\"800\" height=\"300\" src=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/05\/Building-Agentic-AI-Applications-with-Ruby-on-Rails.png\" class=\"attachment-full size-full wp-post-image\" alt=\"Agentic AI Applications with Ruby on Rails\" srcset=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/05\/Building-Agentic-AI-Applications-with-Ruby-on-Rails.png 800w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/05\/Building-Agentic-AI-Applications-with-Ruby-on-Rails-300x113.png 300w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/05\/Building-Agentic-AI-Applications-with-Ruby-on-Rails-768x288.png 768w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/05\/Building-Agentic-AI-Applications-with-Ruby-on-Rails-18x7.png 18w\" sizes=\"(max-width: 800px) 100vw, 800px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\"Building Agentic AI Applications with Ruby on Rails\" href=\"https:\/\/www.railscarma.com\/it\/blog\/building-agentic-ai-applications-with-ruby-on-rails\/?related_post_from=41339\">\r\n        Building Agentic AI Applications with Ruby on Rails  <\/a>\r\n\r\n        <\/div>\r\n              <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\"Cos&#039;\u00e8 e come funziona Offliberty Ruby Gem\" href=\"https:\/\/www.railscarma.com\/it\/blog\/what-is-offliberty-ruby-gem-and-how-it-works\/?related_post_from=41304\">\r\n\r\n      <img decoding=\"async\" width=\"800\" height=\"300\" src=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/What-is-Offliberty-Ruby-Gem-and-How-It-Works.png\" class=\"attachment-full size-full wp-post-image\" alt=\"Gemma di rubino offliberty\" srcset=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/What-is-Offliberty-Ruby-Gem-and-How-It-Works.png 800w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/What-is-Offliberty-Ruby-Gem-and-How-It-Works-300x113.png 300w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/What-is-Offliberty-Ruby-Gem-and-How-It-Works-768x288.png 768w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/What-is-Offliberty-Ruby-Gem-and-How-It-Works-18x7.png 18w\" sizes=\"(max-width: 800px) 100vw, 800px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\"Cos&#039;\u00e8 e come funziona Offliberty Ruby Gem\" href=\"https:\/\/www.railscarma.com\/it\/blog\/what-is-offliberty-ruby-gem-and-how-it-works\/?related_post_from=41304\">\r\n        Cos'\u00e8 e come funziona Offliberty Ruby Gem  <\/a>\r\n\r\n        <\/div>\r\n              <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\"Metodo Rails link_to: Guida completa con esempi\" href=\"https:\/\/www.railscarma.com\/it\/blog\/rails-link_to-method-the-complete-guide-with-examples\/?related_post_from=41296\">\r\n\r\n      <img decoding=\"async\" width=\"800\" height=\"300\" src=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Rails-link_to-Method-The-Complete-Guide-with-Examples.png\" class=\"attachment-full size-full wp-post-image\" alt=\"Metodo Rails link_to\" srcset=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Rails-link_to-Method-The-Complete-Guide-with-Examples.png 800w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Rails-link_to-Method-The-Complete-Guide-with-Examples-300x113.png 300w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Rails-link_to-Method-The-Complete-Guide-with-Examples-768x288.png 768w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Rails-link_to-Method-The-Complete-Guide-with-Examples-18x7.png 18w\" sizes=\"(max-width: 800px) 100vw, 800px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\"Metodo Rails link_to: Guida completa con esempi\" href=\"https:\/\/www.railscarma.com\/it\/blog\/rails-link_to-method-the-complete-guide-with-examples\/?related_post_from=41296\">\r\n        Metodo Rails link_to: Guida completa con esempi  <\/a>\r\n\r\n        <\/div>\r\n              <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\"Soluzioni di integrazione API di terze parti in Ruby on Rails\" href=\"https:\/\/www.railscarma.com\/it\/blog\/third-party-api-integration-solutions-in-ruby-on-rails\/?related_post_from=41264\">\r\n\r\n      <img decoding=\"async\" width=\"800\" height=\"300\" src=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Third-Party-API-Integration-Solutions-in-Ruby-on-Rails.png\" class=\"attachment-full size-full wp-post-image\" alt=\"Soluzioni di integrazione API in Ruby on Rails\" srcset=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Third-Party-API-Integration-Solutions-in-Ruby-on-Rails.png 800w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Third-Party-API-Integration-Solutions-in-Ruby-on-Rails-300x113.png 300w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Third-Party-API-Integration-Solutions-in-Ruby-on-Rails-768x288.png 768w, https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/04\/Third-Party-API-Integration-Solutions-in-Ruby-on-Rails-18x7.png 18w\" sizes=\"(max-width: 800px) 100vw, 800px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\"Soluzioni di integrazione API di terze parti in Ruby on Rails\" href=\"https:\/\/www.railscarma.com\/it\/blog\/third-party-api-integration-solutions-in-ruby-on-rails\/?related_post_from=41264\">\r\n        Soluzioni di integrazione API di terze parti in Ruby on Rails  <\/a>\r\n\r\n        <\/div>\r\n      \r\n  <\/div>\r\n\r\n  <script>\r\n      <\/script>\r\n  <style>\r\n    .related-post {}\r\n\r\n    .related-post .post-list {\r\n      text-align: left;\r\n          }\r\n\r\n    .related-post .post-list .item {\r\n      margin: 10px;\r\n      padding: 10px;\r\n          }\r\n\r\n    .related-post .headline {\r\n      font-size: 14px !important;\r\n      color: #999999 !important;\r\n          }\r\n\r\n    .related-post .post-list .item .post_thumb {\r\n      max-height: 220px;\r\n      margin: 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n          }\r\n\r\n    .related-post .post-list .item .post_title {\r\n      font-size: 14px;\r\n      color: #000000;\r\n      margin: 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n      text-decoration: none;\r\n          }\r\n\r\n    .related-post .post-list .item .post_excerpt {\r\n      font-size: 12px;\r\n      color: #3f3f3f;\r\n      margin: 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n      text-decoration: none;\r\n          }\r\n\r\n    .related-post .owl-dots .owl-dot {\r\n          }\r\n\r\n      <\/style>\r\n      <script>\r\n      jQuery(document).ready(function($) {\r\n        $(\".related-post .post-list\").owlCarousel({\r\n          items: 2,\r\n          responsiveClass: true,\r\n          responsive: {\r\n            0: {\r\n              items: 1,\r\n            },\r\n            768: {\r\n              items: 2,\r\n            },\r\n            1200: {\r\n              items: 2,\r\n            }\r\n          },\r\n                      rewind: true,\r\n                                loop: true,\r\n                                center: false,\r\n                                autoplay: true,\r\n            autoplayHoverPause: true,\r\n                                nav: true,\r\n            navSpeed: 1000,\r\n            navText: ['<i class=\"fas fa-chevron-left\"><\/i>', '<i class=\"fas fa-chevron-right\"><\/i>'],\r\n                                dots: false,\r\n            dotsSpeed: 1200,\r\n                                                    rtl: false,\r\n          \r\n        });\r\n      });\r\n    <\/script>\r\n  <\/div>","protected":false},"excerpt":{"rendered":"<p>Ruby provides simple, elegant, and powerful ways to read from and write to files. The language emphasizes readability and developer happiness, making file I\/O operations straightforward. This guide covers the most common and idiomatic approaches with practical examples. Basic Concepts In Ruby, file operations are typically performed using the File class or the shorter File.open &hellip;<\/p>\n<p class=\"read-more\"> <a class=\"\" href=\"https:\/\/www.railscarma.com\/it\/blog\/third-party-api-integration-solutions-in-ruby-on-rails\/\"> <span class=\"screen-reader-text\">Soluzioni di integrazione API di terze parti in Ruby on Rails<\/span> Leggi altro \"<\/a><\/p>","protected":false},"author":11,"featured_media":40850,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1224],"tags":[],"class_list":["post-40839","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How To Read and Write Files in Ruby (With Examples) - RailsCarma<\/title>\n<meta name=\"description\" content=\"Learn how to read and write files in Ruby with clear examples covering File.read, File.write, blocks, and best practices.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.railscarma.com\/it\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/\" \/>\n<meta property=\"og:locale\" content=\"it_IT\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How To Read and Write Files in Ruby (With Examples) - RailsCarma\" \/>\n<meta property=\"og:description\" content=\"Learn how to read and write files in Ruby with clear examples covering File.read, File.write, blocks, and best practices.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.railscarma.com\/it\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/\" \/>\n<meta property=\"og:site_name\" content=\"RailsCarma - Ruby on Rails Development Company specializing in Offshore Development\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/RailsCarma\/\" \/>\n<meta property=\"article:published_time\" content=\"2026-01-06T14:24:44+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-01-06T14:24:47+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png\" \/>\n\t<meta property=\"og:image:width\" content=\"800\" \/>\n\t<meta property=\"og:image:height\" content=\"300\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"ashish\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@railscarma\" \/>\n<meta name=\"twitter:site\" content=\"@railscarma\" \/>\n<meta name=\"twitter:label1\" content=\"Scritto da\" \/>\n\t<meta name=\"twitter:data1\" content=\"ashish\" \/>\n\t<meta name=\"twitter:label2\" content=\"Tempo di lettura stimato\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minuti\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/\"},\"author\":{\"name\":\"ashish\",\"@id\":\"https:\/\/www.railscarma.com\/#\/schema\/person\/9699b14852b308edfeb03096b33c7a7a\"},\"headline\":\"How To Read and Write Files in Ruby (With Examples)\",\"datePublished\":\"2026-01-06T14:24:44+00:00\",\"dateModified\":\"2026-01-06T14:24:47+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/\"},\"wordCount\":468,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.railscarma.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png\",\"articleSection\":[\"Blogs\"],\"inLanguage\":\"it-IT\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/\",\"url\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/\",\"name\":\"How To Read and Write Files in Ruby (With Examples) - RailsCarma\",\"isPartOf\":{\"@id\":\"https:\/\/www.railscarma.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png\",\"datePublished\":\"2026-01-06T14:24:44+00:00\",\"dateModified\":\"2026-01-06T14:24:47+00:00\",\"description\":\"Learn how to read and write files in Ruby with clear examples covering File.read, File.write, blocks, and best practices.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#breadcrumb\"},\"inLanguage\":\"it-IT\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"it-IT\",\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#primaryimage\",\"url\":\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png\",\"contentUrl\":\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png\",\"width\":800,\"height\":300,\"caption\":\"Read and Write Files in Ruby\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.railscarma.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How To Read and Write Files in Ruby (With Examples)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.railscarma.com\/#website\",\"url\":\"https:\/\/www.railscarma.com\/\",\"name\":\"RailsCarma - Ruby on Rails Development Company specializing in Offshore Development\",\"description\":\"RailsCarma is a Ruby on Rails Development Company in Bangalore. We specialize in Offshore Ruby on Rails Development based out in USA and India. Hire experienced Ruby on Rails developers for the ultimate Web Experience.\",\"publisher\":{\"@id\":\"https:\/\/www.railscarma.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.railscarma.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"it-IT\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.railscarma.com\/#organization\",\"name\":\"RailsCarma\",\"url\":\"https:\/\/www.railscarma.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"it-IT\",\"@id\":\"https:\/\/www.railscarma.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2020\/08\/railscarma_logo.png\",\"contentUrl\":\"https:\/\/www.railscarma.com\/wp-content\/uploads\/2020\/08\/railscarma_logo.png\",\"width\":200,\"height\":46,\"caption\":\"RailsCarma\"},\"image\":{\"@id\":\"https:\/\/www.railscarma.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/RailsCarma\/\",\"https:\/\/x.com\/railscarma\",\"https:\/\/www.linkedin.com\/company\/railscarma\/\",\"https:\/\/myspace.com\/railscarma\",\"https:\/\/in.pinterest.com\/railscarma\/\",\"https:\/\/www.youtube.com\/channel\/UCx3Wil-aAnDARuatTEyMdpg\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.railscarma.com\/#\/schema\/person\/9699b14852b308edfeb03096b33c7a7a\",\"name\":\"ashish\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"it-IT\",\"@id\":\"https:\/\/www.railscarma.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/204411c7d72714bc32d5ac6398e0596896318386bd537860fdd14ce905a79e07?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/204411c7d72714bc32d5ac6398e0596896318386bd537860fdd14ce905a79e07?s=96&d=mm&r=g\",\"caption\":\"ashish\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How To Read and Write Files in Ruby (With Examples) - RailsCarma","description":"Learn how to read and write files in Ruby with clear examples covering File.read, File.write, blocks, and best practices.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.railscarma.com\/it\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/","og_locale":"it_IT","og_type":"article","og_title":"How To Read and Write Files in Ruby (With Examples) - RailsCarma","og_description":"Learn how to read and write files in Ruby with clear examples covering File.read, File.write, blocks, and best practices.","og_url":"https:\/\/www.railscarma.com\/it\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/","og_site_name":"RailsCarma - Ruby on Rails Development Company specializing in Offshore Development","article_publisher":"https:\/\/www.facebook.com\/RailsCarma\/","article_published_time":"2026-01-06T14:24:44+00:00","article_modified_time":"2026-01-06T14:24:47+00:00","og_image":[{"width":800,"height":300,"url":"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png","type":"image\/png"}],"author":"ashish","twitter_card":"summary_large_image","twitter_creator":"@railscarma","twitter_site":"@railscarma","twitter_misc":{"Scritto da":"ashish","Tempo di lettura stimato":"3 minuti"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#article","isPartOf":{"@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/"},"author":{"name":"ashish","@id":"https:\/\/www.railscarma.com\/#\/schema\/person\/9699b14852b308edfeb03096b33c7a7a"},"headline":"How To Read and Write Files in Ruby (With Examples)","datePublished":"2026-01-06T14:24:44+00:00","dateModified":"2026-01-06T14:24:47+00:00","mainEntityOfPage":{"@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/"},"wordCount":468,"commentCount":0,"publisher":{"@id":"https:\/\/www.railscarma.com\/#organization"},"image":{"@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png","articleSection":["Blogs"],"inLanguage":"it-IT","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/","url":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/","name":"How To Read and Write Files in Ruby (With Examples) - RailsCarma","isPartOf":{"@id":"https:\/\/www.railscarma.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#primaryimage"},"image":{"@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png","datePublished":"2026-01-06T14:24:44+00:00","dateModified":"2026-01-06T14:24:47+00:00","description":"Learn how to read and write files in Ruby with clear examples covering File.read, File.write, blocks, and best practices.","breadcrumb":{"@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#breadcrumb"},"inLanguage":"it-IT","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/"]}]},{"@type":"ImageObject","inLanguage":"it-IT","@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#primaryimage","url":"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png","contentUrl":"https:\/\/www.railscarma.com\/wp-content\/uploads\/2026\/01\/How-To-Read-and-Write-Files-in-Ruby-With-Examples.png","width":800,"height":300,"caption":"Read and Write Files in Ruby"},{"@type":"BreadcrumbList","@id":"https:\/\/www.railscarma.com\/blog\/how-to-read-and-write-files-in-ruby-with-examples\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.railscarma.com\/"},{"@type":"ListItem","position":2,"name":"How To Read and Write Files in Ruby (With Examples)"}]},{"@type":"WebSite","@id":"https:\/\/www.railscarma.com\/#website","url":"https:\/\/www.railscarma.com\/","name":"RailsCarma - Societ\u00e0 di sviluppo Ruby on Rails specializzata nello sviluppo offshore","description":"RailsCarma \u00e8 una societ\u00e0 di sviluppo Ruby on Rails a Bangalore. Siamo specializzati nello sviluppo offshore di Ruby on Rails con sede negli Stati Uniti e in India. Assumi sviluppatori esperti di Ruby on Rails per la migliore esperienza Web.","publisher":{"@id":"https:\/\/www.railscarma.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.railscarma.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"it-IT"},{"@type":"Organization","@id":"https:\/\/www.railscarma.com\/#organization","name":"RailsCarma","url":"https:\/\/www.railscarma.com\/","logo":{"@type":"ImageObject","inLanguage":"it-IT","@id":"https:\/\/www.railscarma.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.railscarma.com\/wp-content\/uploads\/2020\/08\/railscarma_logo.png","contentUrl":"https:\/\/www.railscarma.com\/wp-content\/uploads\/2020\/08\/railscarma_logo.png","width":200,"height":46,"caption":"RailsCarma"},"image":{"@id":"https:\/\/www.railscarma.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/RailsCarma\/","https:\/\/x.com\/railscarma","https:\/\/www.linkedin.com\/company\/railscarma\/","https:\/\/myspace.com\/railscarma","https:\/\/in.pinterest.com\/railscarma\/","https:\/\/www.youtube.com\/channel\/UCx3Wil-aAnDARuatTEyMdpg"]},{"@type":"Person","@id":"https:\/\/www.railscarma.com\/#\/schema\/person\/9699b14852b308edfeb03096b33c7a7a","name":"ashish","image":{"@type":"ImageObject","inLanguage":"it-IT","@id":"https:\/\/www.railscarma.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/204411c7d72714bc32d5ac6398e0596896318386bd537860fdd14ce905a79e07?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/204411c7d72714bc32d5ac6398e0596896318386bd537860fdd14ce905a79e07?s=96&d=mm&r=g","caption":"ashish"}}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/posts\/40839","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/users\/11"}],"replies":[{"embeddable":true,"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/comments?post=40839"}],"version-history":[{"count":0,"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/posts\/40839\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/media\/40850"}],"wp:attachment":[{"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/media?parent=40839"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/categories?post=40839"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.railscarma.com\/it\/wp-json\/wp\/v2\/tags?post=40839"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}