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:
Gemfilelists a project's gems for Bundler, andGemfile.lock(not Ruby) records the exact versions.Rakefiledefines tasks for Rake, Ruby's build tool:rake test,rake build.*.gemspec** describes a gem: its name, version, files and dependencies.config.rustarts a Rack web application, the layer underneath Rails and Sinatra.VagrantfileandPodfileconfigure 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.
#!/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
#!/usr/bin/env rubyThe shebang
Used when the file is run as a program on macOS or Linux (
./greeter.rb): it runs the file with the firstrubyon the PATH, which respects version managers like rbenv. Ruby treats it as a comment. - 2
# frozen_string_literal: trueA 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
require "json"Loading a library
requiresearches Ruby's load path: the standard library and installed gems. Each file is loaded once, however many times it's required. - 4
require_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
.rbextension is left off. - 5
module GreeterA module
A namespace that keeps names like
Personfrom clashing with other code. Module and class names are constants, so they start with a capital letter. - 6
attr_reader :nameAn attribute reader
Writes a
namemethod that returns@name.:nameis a symbol, an immutable identifier. - 7
def initialize(name = DEFAULT_NAME)The constructor
Runs when you call
Person.new.@nameis an instance variable, private to each object. The argument has a default value. - 8
"Hello, #{name}!"An implicit return
A method returns its last expression, so no
returnis needed.#{…}inserts a value into a double-quoted string; single quotes don't interpolate. - 9
names.map { |name| … }A block
Code passed to a method, here run once for each name. Braces are used for one-line blocks,
do … endfor longer ones. - 10
if __FILE__ == $PROGRAM_NAMEThe 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
- 1You start the interpreter with the file:
ruby greeter.rb, on any operating system. - 2It reads the magic comments at the top, which set the file's encoding and whether string literals are frozen.
- 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.
- 4It compiles the code to bytecode for Ruby's virtual machine, in memory. Unlike Python, Ruby writes no cache files next to your code.
- 5It runs the file from top to bottom.
class,moduleanddefare ordinary statements that create classes and methods as they run, and eachrequireruns the required file the first time. - 6It exits at the end of the file, or at
exit,abortor 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
| Windows | macOS | Linux | |
|---|---|---|---|
| Get Ruby | RubyInstaller, or Ruby inside WSL | Homebrew, or a version manager such as rbenv, chruby or mise | The distribution's ruby package, or a version manager |
| Run a file | ruby script.rb | ruby script.rb | ruby script.rb |
| In a project with a Gemfile | bundle exec ruby script.rb | bundle exec ruby script.rb | bundle exec ruby script.rb |
| Run it as a program | Through ruby; shebangs aren't used | chmod +x script.rb, then ./script.rb | chmod +x script.rb, then ./script.rb |
- Check which Ruby you have:
ruby -v. Projects often name the version they need in a.ruby-versionfile, 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.rbprintsSyntax OKor the error, and exits with status 1 on failure. - See warnings:
ruby -w file.rbruns 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:
irbfor an interactive prompt,ri String#upcasefor 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: truemust be in the first comment section;# encoding: …must be on line 1, or line 2 after a shebang.# warn_indent: trueand# shareable_constant_value:also exist. - Frozen string literals. With the magic comment,
"text" << "more"raisesFrozenError. 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 -wwarns 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.rbdefinesUserProfile. 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 theDATAconstant.
A gem or larger project puts its code under lib/, with one main file that requires the rest:
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.rbDependencies
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: 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"
endbundle installinstalls the gems and writesGemfile.lockwith the exact version of every gem, including the gems they depend on. Commit the lock file, so every machine runs the same versions.bundle execruns a command with exactly those versions, for examplebundle exec rake test. Without it, Ruby may load a different installed version.~> 4.0is the pessimistic operator: 4.0 or newer, but below 5.0.- Libraries leave the standard library over time. Ruby 3.4 turned
csv,base64,bigdecimaland others into bundled gems, and Ruby 4.0 did the same forostruct,pstoreandlogger. They still come with Ruby, but a Bundler project must list them in its Gemfile orrequirefails.
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.
| Version | Released | What changed for .rb files |
|---|---|---|
| 1.8 | 2003 | The long-lived version that early Rails was built on. |
| 1.9 | December 2007 | Strings became encoding-aware, the magic encoding comment arrived, and the { name: "Ada" } hash syntax. |
| 2.0 | February 2013 | UTF-8 became the default source encoding, so most files no longer need an encoding comment. |
| 2.3 | December 2015 | The # frozen_string_literal: true magic comment and the safe navigation operator &.. |
| 3.0 | December 2020 | RBS type signature files (.rbs) and Ractors for parallel code. |
| 3.4 | December 2024 | Prism 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.0 | December 2025 | Ruby 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 message | Usual cause | Fix |
|---|---|---|
| ruby: command not found / 'ruby' is not recognized… | Ruby isn't installed, or isn't on the PATH | Install 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 project | Add 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 for | Prefix the command with bundle exec |
| syntax error … unexpected end-of-input | An end is missing, so a def, do or if is never closed | Run 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: true | Build strings from a mutable copy: +"" or .dup |
| invalid multibyte char (UTF-8) | The file was saved in another encoding, such as Windows-1252 | Re-save it as UTF-8, or add an # encoding: magic comment |
| /usr/bin/env: 'ruby\r': No such file or directory | Windows (CRLF) line endings on a script run as ./script.rb | Convert to LF with dos2unix or your editor |
| uninitialized constant UserProfile (NameError) | In Rails, a file name that doesn't match its class name | Rename 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 installevaluates 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
evaluser input, orMarshal.loaduntrusted data, which can create arbitrary objects. For YAML, useYAML.safe_loadon anything you didn't write. - Keep secrets out of
.rbfiles. 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.
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.
Comments 1 and 2: shebang and magic comment
#!/usr/bin/env rubyon line 1 and# frozen_string_literal: trueon line 2, the two lines most Ruby scripts start with.Comments 3 and 4: require and a module
require "json"loads a library that ships with Ruby, and amodulekeeps the script's names in one namespace.Comments 5 and 6: Data and a heredoc
Data.definecreates an immutable value class, and a squiggly heredoc (<<~TEXT) holds the sample data, including one deliberately bad line.Comment 7: parsing with a rescue
each_line.with_indexandfilter_map, with arescueinside the block: the bad line produces a warning on stderr and is skipped.Comment 8: Enumerable
group_by,transform_values,sumandsort_bychained together to total each category.Comment 9: frozen strings in practice
Because literals are frozen, the report is built in a mutable copy made with
+"".format()pads the columns.Comments 10 and 11: the entry point
if __FILE__ == $PROGRAM_NAMEruns the script part only when the file is executed;abortreports a missing file and exits with status 1;--jsonprints the items withJSON.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 underruby -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
FrozenErrorcaught 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.rbworks (with a warning under-w);./sample-crlf.rbon macOS or Linux fails with theruby\rerror.- 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
defhas no matchingend. Clearly labelled;ruby -creports 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 -cshould printSyntax OKfor every sample exceptsample-syntax-error.rb; use that one to check how your CI or editor reports errors. - Ruby upgrades: delete line 1 of
sample-frozen-string.rband run it withruby -W:deprecatedon Ruby 3.4 or later to see the chilled-string warning. - Line endings: pass
sample-crlf.rbthrough Git or your pipeline and check whether the CRLFs survive; if they became LFs,./sample-crlf.rbstarts working. - Upload limits:
sample-100kb.rbis 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
- Ruby documentation: Code comments and magic comments
- Ruby 3.4 release notes (NEWS)
- Ruby 4.0.0 release announcement
- Download Ruby: current versions (ruby-lang.org)
- RubyGems guides: Using Bundler in applications
Last reviewed 27 October 2026.