File types · Explainer

The Ruby file (.rb)

A Ruby file is a plain-text program that the Ruby interpreter runs, from small scripts to whole Rails web applications. This guide explains what's inside one, how to run and check it, the file-level conventions and errors worth knowing, and has free sample Ruby files to download for testing.

At a glance

Full name
Ruby source file
Extensions
.rb; Ruby code also lives in Gemfile, Rakefile and *.gemspec files
MIME type
None registered; application/x-ruby is the usual one, and text/x-ruby also appears
Kind
Plain text (source code)
Encoding
UTF-8 by default; an # encoding: magic comment declares another
Owner
The Ruby core team, led by its creator; the reference interpreter is CRuby (MRI). ISO/IEC 30170:2012 standardises an early version of the language
First released
1995, by Yukihiro Matsumoto ("Matz") in Japan
Current version
Ruby 4.0, released on 25 December 2025; 3.4 is still maintained
Runs with
ruby file.rb on Windows, macOS and Linux
Comments
# line; =begin … =end for blocks
Magic number
None; often starts with #!/usr/bin/env ruby and a # frozen_string_literal: true comment

The basics

What is an RB file?

An .rb file holds a program written in Ruby, a general-purpose programming language designed to be pleasant to read and write. A Ruby on Rails web application is hundreds of .rb files; so is a command-line tool, a test suite, or a Homebrew formula that tells the Mac package manager how to install something. The file is plain text, so any text editor can open it.

Ruby files need the Ruby interpreter to run: there's no compile step and no .exe. The interpreter reads the file, checks the syntax, and runs it. In a project, the gems (Ruby libraries) it uses are listed in a Gemfile and installed by Bundler.

Not every Ruby file ends in .rb. Several tools use Ruby as their configuration language, in files with fixed names:

  • Gemfile lists a project's gems for Bundler, and Gemfile.lock (not Ruby) records the exact versions.
  • Rakefile defines tasks for Rake, Ruby's build tool: rake test, rake build.
  • *.gemspec** describes a gem: its name, version, files and dependencies.
  • config.ru starts a Rack web application, the layer underneath Rails and Sinatra.
  • Vagrantfile and Podfile configure Vagrant virtual machines and CocoaPods for iOS projects.

Anatomy

What's inside a Ruby file

A Ruby file is a list of expressions that run from top to bottom. Classes, modules and methods are defined as the file runs, and every block ends with end. Here is a small but complete script, part by part.

greeter.rb
#!/usr/bin/env ruby
# frozen_string_literal: true

require "json"
require_relative "lib/formatter"

# Greets people by name.
module Greeter
  DEFAULT_NAME = "world"

  class Person
    attr_reader :name

    def initialize(name = DEFAULT_NAME)
      @name = name
    end

    def greeting
      "Hello, #{name}!"
    end
  end

  def self.run(names)
    names.map { |name| Person.new(name).greeting }
  end
end

if __FILE__ == $PROGRAM_NAME
  puts JSON.generate(Greeter.run(ARGV))
end
  1. 1#!/usr/bin/env ruby

    The shebang

    Used when the file is run as a program on macOS or Linux (./greeter.rb): it runs the file with the first ruby on the PATH, which respects version managers like rbenv. Ruby treats it as a comment.

  2. 2# frozen_string_literal: true

    A magic comment

    A comment that changes how Ruby reads this file only. This one makes every string literal read-only. It must be in the first comment section of the file; an # encoding: comment must be on line 1, or line 2 after a shebang.

  3. 3require "json"

    Loading a library

    require searches Ruby's load path: the standard library and installed gems. Each file is loaded once, however many times it's required.

  4. 4require_relative "lib/formatter"

    Loading another file of yours

    Resolves the path from this file's folder, not from the folder you happen to run Ruby in. The .rb extension is left off.

  5. 5module Greeter

    A module

    A namespace that keeps names like Person from clashing with other code. Module and class names are constants, so they start with a capital letter.

  6. 6attr_reader :name

    An attribute reader

    Writes a name method that returns @name. :name is a symbol, an immutable identifier.

  7. 7def initialize(name = DEFAULT_NAME)

    The constructor

    Runs when you call Person.new. @name is an instance variable, private to each object. The argument has a default value.

  8. 8"Hello, #{name}!"

    An implicit return

    A method returns its last expression, so no return is needed. #{…} inserts a value into a double-quoted string; single quotes don't interpolate.

  9. 9names.map { |name| … }

    A block

    Code passed to a method, here run once for each name. Braces are used for one-line blocks, do … end for longer ones.

  10. 10if __FILE__ == $PROGRAM_NAME

    The entry-point check

    True only when this file is the one being run, not when another file requires it. That lets one file work both as a script and as a library.

Under the hood

What happens when you run a Ruby file

  1. 1You start the interpreter with the file: ruby greeter.rb, on any operating system.
  2. 2It reads the magic comments at the top, which set the file's encoding and whether string literals are frozen.
  3. 3It parses the whole file. A syntax error anywhere means nothing runs. Since Ruby 3.4 the default parser is Prism, which reports errors with different wording from earlier versions.
  4. 4It compiles the code to bytecode for Ruby's virtual machine, in memory. Unlike Python, Ruby writes no cache files next to your code.
  5. 5It runs the file from top to bottom. class, module and def are ordinary statements that create classes and methods as they run, and each require runs the required file the first time.
  6. 6It exits at the end of the file, or at exit, abort or an unhandled exception, which prints a backtrace and exits with status 1.

irb: Ruby without a file

irb opens an interactive Ruby prompt where each line runs as you type it. irb -r ./greeter.rb loads a file first, so you can try out its classes and methods by hand.

How to

How to run, edit and check a Ruby file

WindowsmacOSLinux
Get RubyRubyInstaller, or Ruby inside WSLHomebrew, or a version manager such as rbenv, chruby or miseThe distribution's ruby package, or a version manager
Run a fileruby script.rbruby script.rbruby script.rb
In a project with a Gemfilebundle exec ruby script.rbbundle exec ruby script.rbbundle exec ruby script.rb
Run it as a programThrough ruby; shebangs aren't usedchmod +x script.rb, then ./script.rbchmod +x script.rb, then ./script.rb
  • Check which Ruby you have: ruby -v. Projects often name the version they need in a .ruby-version file, which version managers read automatically when you enter the folder.
  • Leave the system Ruby alone. Where an operating system includes its own Ruby, it's there for the system's tools. Install gems and newer versions in your own Ruby instead of using sudo gem install.
  • Run one-liners with ruby -e 'puts 6 * 7'.
  • Read or edit it: any plain-text editor works. VS Code with the Ruby LSP extension, or RubyMine, add autocompletion, go-to-definition and debugging.
  • Check the syntax without running it: ruby -c file.rb prints Syntax OK or the error, and exits with status 1 on failure.
  • See warnings: ruby -w file.rb runs it with extra warnings, such as unused variables and mismatched indentation.
  • Lint and format: RuboCop checks code against the community Ruby style guide and can fix much of it with rubocop -a.
  • Experiment: irb for an interactive prompt, ri String#upcase for documentation in the terminal.

The rules

Magic comments, file names and project layout

  • Magic comments affect only the file they're in. # frozen_string_literal: true must be in the first comment section; # encoding: … must be on line 1, or line 2 after a shebang. # warn_indent: true and # shareable_constant_value: also exist.
  • Frozen string literals. With the magic comment, "text" << "more" raises FrozenError. Without it, Ruby 3.4 and later treat literals as "chilled": changing one still works but triggers a deprecation warning when deprecation warnings are on (ruby -W:deprecated). It's a step towards frozen literals by default, which is why most Ruby files start with the comment.
  • Encoding. UTF-8 is the default source encoding. A file saved in another encoding without a magic comment stops with invalid multibyte char (UTF-8). A UTF-8 byte order mark is accepted by Ruby, but breaks the shebang on macOS and Linux.
  • Line endings. Ruby reads CRLF files, but a shebang line ending in CRLF fails when run as ./script.rb. ruby -w warns about it: "shebang line ending with \r may cause problems".
  • File names are snake_case.rb, named after the class or module inside: user_profile.rb defines UserProfile. Rails depends on this: its autoloader (Zeitwerk) finds classes by file name, so a mismatch means "uninitialized constant".
  • __END__ on a line of its own ends the program. Anything after it isn't parsed, and the script can read it through the DATA constant.

A gem or larger project puts its code under lib/, with one main file that requires the rest:

gem layout
my_gem/
  Gemfile               gems the project needs
  Gemfile.lock          exact versions Bundler chose: commit it
  my_gem.gemspec        the gem's name, version and dependencies
  Rakefile              tasks such as rake test (Ruby code, no extension)
  lib/
    my_gem.rb           what require "my_gem" loads
    my_gem/
      version.rb        defines MyGem::VERSION
  exe/
    my_gem              a command-line entry point with a shebang
  test/
    test_my_gem.rb

Dependencies

Gemfile, Gemfile.lock and Bundler

Gems are Ruby's packages, published on rubygems.org. A project lists the gems it needs in a Gemfile, which is itself Ruby code:

Gemfile
# Gemfile: Ruby code that Bundler reads
source "https://rubygems.org"

ruby ">= 3.3"

gem "sinatra", "~> 4.0"   # 4.x, but not 5.0
gem "csv"                 # a bundled gem since Ruby 3.4

group :test do
  gem "minitest"
end
  • bundle install installs the gems and writes Gemfile.lock with the exact version of every gem, including the gems they depend on. Commit the lock file, so every machine runs the same versions.
  • bundle exec runs a command with exactly those versions, for example bundle exec rake test. Without it, Ruby may load a different installed version.
  • ~> 4.0 is the pessimistic operator: 4.0 or newer, but below 5.0.
  • Libraries leave the standard library over time. Ruby 3.4 turned csv, base64, bigdecimal and others into bundled gems, and Ruby 4.0 did the same for ostruct, pstore and logger. They still come with Ruby, but a Bundler project must list them in its Gemfile or require fails.

History

Ruby versions that matter for files

A Ruby file doesn't declare its version. Projects state it in .ruby-version, in the Gemfile's ruby line or in the gemspec. New Ruby versions traditionally come out on 25 December.

VersionReleasedWhat changed for .rb files
1.82003The long-lived version that early Rails was built on.
1.9December 2007Strings became encoding-aware, the magic encoding comment arrived, and the { name: "Ada" } hash syntax.
2.0February 2013UTF-8 became the default source encoding, so most files no longer need an encoding comment.
2.3December 2015The # frozen_string_literal: true magic comment and the safe navigation operator &..
3.0December 2020RBS type signature files (.rbs) and Ractors for parallel code.
3.4December 2024Prism became the default parser, it names a block's parameter, and mutating a string literal in a file without the magic comment can warn.
4.0December 2025Ruby Box (isolated namespaces, with RUBY_BOX=1), the ZJIT compiler (--zjit), and several libraries moved out of the default gems.

Troubleshooting

Errors when opening or running a Ruby file

Error messageUsual causeFix
ruby: command not found / 'ruby' is not recognized…Ruby isn't installed, or isn't on the PATHInstall Ruby; on Windows, reopen the terminal after RubyInstaller finishes
cannot load such file -- nokogiri (LoadError)The gem isn't installed, or isn't in the Gemfile of a Bundler projectAdd it to the Gemfile and run bundle install
You have already activated rake 13.x, but your Gemfile requires…A command ran with a different gem version than the lock file asks forPrefix the command with bundle exec
syntax error … unexpected end-of-inputAn end is missing, so a def, do or if is never closedRun ruby -c file.rb and check the blocks above the line it reports
can't modify frozen String (FrozenError)Changing a string literal in a file with frozen_string_literal: trueBuild strings from a mutable copy: +"" or .dup
invalid multibyte char (UTF-8)The file was saved in another encoding, such as Windows-1252Re-save it as UTF-8, or add an # encoding: magic comment
/usr/bin/env: 'ruby\r': No such file or directoryWindows (CRLF) line endings on a script run as ./script.rbConvert to LF with dos2unix or your editor
uninitialized constant UserProfile (NameError)In Rails, a file name that doesn't match its class nameRename userprofile.rb to user_profile.rb, or the class to match

Security

Is it safe to open or run a Ruby file?

Opening an .rb file in a text editor only shows its code. Running it gives it your user account's permissions: Ruby has no sandbox. Points worth knowing:

  • A Gemfile is code. bundle install evaluates the Gemfile and gems can compile native extensions while installing, so treat installing a stranger's project like running their program.
  • Shell commands and user input don't mix. Backticks, system("convert #{file}") and %x() pass a string to the shell, where crafted input can run other commands. Pass arguments separately instead: system("convert", file).
  • Never eval user input, or Marshal.load untrusted data, which can create arbitrary objects. For YAML, use YAML.safe_load on anything you didn't write.
  • Keep secrets out of .rb files. Read API keys from environment variables or Rails' encrypted credentials, so they don't end up in version control.

Free downloads

Sample Ruby files to download

Free sample Ruby files for testing editors, syntax highlighters, linters, upload filters and size limits. All run with Ruby 3.2 or later, except sample-syntax-error.rb, which fails on purpose.

sample-script.rb · 3.1 KBDownloadOpen
Loading…

What's inside sample-script.rb

The file is commented: open it in a text editor and each numbered comment marks one of these parts. Run it with ruby sample-script.rb, or add --json for JSON output.

  1. Comments 1 and 2: shebang and magic comment

    #!/usr/bin/env ruby on line 1 and # frozen_string_literal: true on line 2, the two lines most Ruby scripts start with.

  2. Comments 3 and 4: require and a module

    require "json" loads a library that ships with Ruby, and a module keeps the script's names in one namespace.

  3. Comments 5 and 6: Data and a heredoc

    Data.define creates an immutable value class, and a squiggly heredoc (<<~TEXT) holds the sample data, including one deliberately bad line.

  4. Comment 7: parsing with a rescue

    each_line.with_index and filter_map, with a rescue inside the block: the bad line produces a warning on stderr and is skipped.

  5. Comment 8: Enumerable

    group_by, transform_values, sum and sort_by chained together to total each category.

  6. Comment 9: frozen strings in practice

    Because literals are frozen, the report is built in a mutable copy made with +"". format() pads the columns.

  7. Comments 10 and 11: the entry point

    if __FILE__ == $PROGRAM_NAME runs the script part only when the file is executed; abort reports a missing file and exits with status 1; --json prints the items with JSON.pretty_generate.

All sample Ruby files

  • Commented sample script

    sample-script.rb · 3.1 KB (3,181 bytes)

    Totals a small expense list by category, with numbered comments explaining each part: magic comment, module, Data, heredoc, blocks, error handling and the entry-point check. Runs without warnings under ruby -w.

    • Checking editors, highlighters and linters on modern Ruby
    • Teaching the parts of a Ruby file
  • UTF-8 encoding test

    sample-utf8.rb · 1.7 KB (1,698 bytes)

    Greetings in 12 languages plus symbols and emoji, with each string's length in characters and bytes, Unicode case mapping and normalisation, and a method with a non-ASCII name.

    • Spotting encoding bugs in editors and pipelines
    • Testing right-to-left and CJK text in code viewers
  • frozen_string_literal demo

    sample-frozen-string.rb · 1.1 KB (1,095 bytes)

    Shows what the magic comment changes: a FrozenError caught and reported, mutable copies with +"", unfrozen interpolated strings, and identical literals sharing one object.

    • Seeing the magic comment's effect, with and without it
    • Testing Ruby upgrades for chilled-string warnings
  • Windows (CRLF) line endings

    sample-crlf.rb · 894 bytes

    A script with a shebang, saved with CRLF line endings. ruby sample-crlf.rb works (with a warning under -w); ./sample-crlf.rb on macOS or Linux fails with the ruby\r error.

    • Testing line-ending conversion in Git, editors and upload pipelines
    • Reproducing the CRLF shebang error
  • Missing end (deliberate syntax error)

    sample-syntax-error.rb · 573 bytes

    A method whose def has no matching end. Clearly labelled; ruby -c reports a syntax error at the end of the file and exits with status 1.

    • Testing how editors, linters and CI report syntax errors
    • Comparing error messages between Ruby versions
  • 100 KB Ruby file

    sample-100kb.rb · 100 KB (102,400 bytes)

    A table of the 14,390 happy numbers up to 100,112 and a check that it's complete, padded with a comment to exactly 102,400 bytes.

    • Upload and size-limit tests
    • Parser, highlighter and editor performance

Ways to test with them

  • Syntax checks: ruby -c should print Syntax OK for every sample except sample-syntax-error.rb; use that one to check how your CI or editor reports errors.
  • Ruby upgrades: delete line 1 of sample-frozen-string.rb and run it with ruby -W:deprecated on Ruby 3.4 or later to see the chilled-string warning.
  • Line endings: pass sample-crlf.rb through Git or your pipeline and check whether the CRLFs survive; if they became LFs, ./sample-crlf.rb starts working.
  • Upload limits: sample-100kb.rb is exactly 102,400 bytes, for testing a limit at the boundary.

Free to use for testing, teaching and demos, commercially or not, with no attribution needed. A link back to this page is always appreciated.

Put it online

Have a Ruby file? Give it a link.

Drop an .rb file on 99helpers and it gets its own address in seconds. Opening the link shows the code as plain text in the browser: it is never run on the server, so it's a safe way to share a script for review or download.

Questions

Ruby files, frequently asked

What is an .rb file?

A Ruby source file: a plain-text program written in the Ruby language. The Ruby interpreter runs it, and any text editor can open it.

How do I run an .rb file?

Install Ruby, open a terminal in the file's folder and run ruby file.rb. In a project with a Gemfile, run bundle install once, then bundle exec ruby file.rb.

How do I check a Ruby file for syntax errors?

Run ruby -c file.rb. It prints Syntax OK, or the first syntax error with its line number, without running the code.

What does # frozen_string_literal: true do?

It makes every string literal in that file read-only, which saves memory and prevents accidental changes. Trying to change one raises FrozenError; use +"" or .dup when you need a mutable string.

What's the difference between require and require_relative?

require searches Ruby's load path, for libraries and gems. require_relative loads a file by its path relative to the current file, which is what you want for files in your own project.

What are Gemfile and Gemfile.lock?

The Gemfile lists the gems a project needs, in Ruby code. Gemfile.lock records the exact versions Bundler installed, so everyone gets the same ones; commit both to version control.

Is Ruby the same as Ruby on Rails?

No. Ruby is the programming language; Rails is a web framework written in Ruby. A Rails application is made of many .rb files.

Is it safe to run an .rb file?

Only if you trust where it came from or have read it. Ruby scripts run with your full user permissions. Opening one in a text editor is safe.

Related formats

Other file types explained

Keep going

Related

Sources

Last reviewed 27 October 2026.