๐ The Missing Cheatsheet for Ruby
Repo lifeparticle/Ruby-Cheatsheet, read from GitHub 6 h ago. lifeparticle has not joined Take My Repo.
lifeparticle/Ruby-Cheatsheet is a public repo on GitHub by lifeparticle. ๐ The Missing Cheatsheet for Ruby. It declares the MIT license on GitHub. It is written mainly in Ruby, has 218 stars and last changed on 2026-10-31. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-22.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.

include?)First things first, make sure you have Ruby installed on your machine.
Debian GNU/Linux and Ubuntu use the apt package manager. You can use it like this:
$ sudo apt-get install ruby-full
On Windows, you can use the Windows Package Manager CLI to install Ruby:
> winget install RubyInstallerTeam.Ruby
Homebrew (macOS) Ruby versions 2.0 and above are included by default in macOS releases since at least El Capitan (10.11).
Homebrew is a commonly used package manager on macOS. Installing Ruby using Homebrew is easy:
$ brew install ruby
This should install the latest Ruby version.
List all the installed Ruby versions:
which -a ruby
# /usr/bin/ruby
Get information about currently used Ruby:
ruby -v
# ruby 2.6.3p62 (2019-04-16 revision 67580) [universal.arm64e-darwin20]
gem env
In case you donโt want to install Ruby natively, you can use docker.
docker run -it --rm ruby:latest
# check which version of Ruby you're running
RUBY_VERSION
Run a specific version of Ruby.
docker run -it --rm ruby:2.7
# check which version of Ruby you're running
RUBY_VERSION
rbenv is a version manager tool for the Ruby programming language on Unix-like systems. It is useful for switching between multiple Ruby versions on the same machine and for ensuring that each project you are working on always runs on the correct Ruby version.
brew install rbenv ruby-build
sudo apt install rbenv
Load rbenv
# run this and follow the printed instructions:
rbenv init
Restart terminal for the changes to take effect.
# list latest stable versions:
rbenv install -l
# list all local versions:
rbenv install -L
# install a Ruby version:
rbenv install 3.1.2
rbenv global 3.1.2 # set the default Ruby version for this machine
# or:
rbenv local 3.1.2 # set the Ruby version for this directory
rbenv local --unset
rbenv version # Displays the currently active Ruby version
=> 1.9.3-p327 (set by /Users/sam/.rbenv/version)
RVM allows you to install and manage multiple installations of Ruby on your system. It can also manage different gemsets. It is available for macOS, Linux, or other UNIX-like operating systems.
\curl -sSL https://get.rvm.io | bash -s stable
rvm list
rvm install 3.0.1
rvm list
rvm use 3.0.1
# access the bash for executing the following commands
docker run -it --rm ruby:latest bash
gem install bundler
bundle -v
gem update bundler
gem uninstall bundler
Gemfile is a configuration file for Bundler (also a gem), which contains a list of gems for your project (dependencies).
# specify your gems in a Gemfile in your projectโs root
ruby '2.5.6'
source 'https://rubygems.org'
gem 'nokogiri'
gem 'rack', '~>1.1'
gem 'rspec', :require => 'spec'
# install all the gems in the Gemfile
bundle install
gem install bundler -v 1.17
gem install minitest -v 5.8.4
bundle update nokogiri
Bundler attempted to update gem_name but its version stayed the same.
gem_name.gem_name.'gem_name', '~> 2.0.5'
bundle update
Ruby is a pure object-oriented and interpreted (executes the code at runtime) programming language invented in the mid-90s by Yukihiro Matsumoto. In Ruby, everything is an object. It is easy to learn with dynamic typing and automatic memory management.
With the idea that programming should be enjoyable for programmers, it was created to increase programmer productivity. It emphasizes the necessity for software to be understood by humans first and computers second.
Ruby will be quite familiar to Python, and Perl developers (and to a lesser extent C# and JavaScript developers) as Ruby was heavily inspired by Perl in certain areas (as was Python). Ruby is less related to languages like C, C++, or Java because these languages are compiled (not interpreted), statically typed, and focused on performance rather than flexibility and conciseness.
Ruby comes with a program that will show the results of any Ruby statements you feed it. Playing with Ruby code in interactive sessions like this is a terrific way to learn the language.
Open up IRB (which stands for Interactive Ruby).
Terminal and type irb, then hit enter.shell and type irb and hit enter.Interactive Ruby from the Ruby section
of your Start Menu.1.next # 2
To test the above code, type the irb command from your shell to initiate the interpreter.

| Reserved Word | Description |
|---|---|
__ENCODING__ |
The script encoding of the current file. |
__LINE__ |
The line number of this keyword in the current file. |
__FILE__ |
The path to the current file. |
| BEGIN | Code enclosed in { } to run before program runs |
| END | enclosed in { } to run when program ends |
| alias | Create alias for existing method, operator, global variable |
| and | Logical AND Operator |
| begin | Begins a block of code |
| break | Terminate a loop |
| case | Comparing an expression with matching when clause which closes with end |
| class | Defining a class |
| def | Defining a function/method |
| defined? | To check if some variable, function exists or not |
| do | Begins a code block and execute code in the block, this ends with end keyword |
| else | Executes following code if previous conditional is not true |
| elsif | An alternate condition for an if expression. |
| end | For ending a code block which started with keywords like begin, class, def, do, if |
| ensure | Always execute at block termination |
| false | Logical Boolean false value |
| for | Begin a for loop |
| if | Executes the code block in case conditional statement for if is true |
| in | Used with for loop |
| module | Defining a module |
| next | Jump to point immediately before evaluation of loopโs conditional |
| nil | Empty or invalid or always false |
| not | Logical Negation Operator |
| or | Logical Or Operator |
| redo | Jump after a loop conditional |
| rescue | Evaluates the expression after an exception is raised |
| retry | โข When called outside of rescue repates the method call โข When called inside rescue jumps to top of block |
| return | Returns a value from a method or code block |
| self | Current Object |
| super | Calls method of same name in the superclass |
| then | Separator used with if, unless, when, case, rescue |
| true | Logical Boolean true |
| undef | Makes a method/function undefined in current class |
| until | Execute code block while conditional statement is false |
| when | Starts a clause under case statement |
| while | Executes the code block, until the conditional statement becomes false |
| yield | Executes the code block which is passed to a method |
[Further reading][1]
# single line comment
=begin
multiline
comment
=end
=begin Comment line 1 =end
puts "Hello world!" # Inline comment about the code
We put a space between the contents of the comment & the start of the comment to make it easier to read.
I prefer # for multiline comments because it maintains my style guide and is easier to read.
| Logical operators | Bitwise operators | Arithmetic operators | Assignment operators | Comparison operators | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
|
|
# Addition
1 + 1 #=> 2
# Subtraction
2 - 1 #=> 1
# Multiplication
2 * 2 #=> 4
# Division
10 / 5 #=> 2
17 / 5 #=> 3, not 3.4
17 / 5.0 #=> 3.4
# Exponent
2 ** 2 #=> 4
3 ** 4 #=> 81
# Modulus (find the remainder of division)
8 % 2 #=> 0 (8 / 2 = 4; no remainder)
10 % 4 #=> 2 (10 / 4 = 2 with a remainder of 2)
a = 10
b = 20
a == b #=> false
a != b #=> true
a > b #=> false
a < b #=> true
a >= b #=> false
a <= b #=> true
# Comparison Operator
a <=> b #=> -1
c = 20
c <=> b #=> 0
c <=> a #=> 1
# Used to test equality within a when clause of a case statement.
(1...10) === 5 #=> true
# True if the receiver and argument have both the same type and equal values.
1.eql?(1.0) #=> false
c = a + b #=> 30
c += a #=> 40
c -= a #=> 30
c *= a #=> 300
c /= a #=> 30
c %= a #=> 3
c **= a #=> 59049
# Ruby Parallel Assignment
a = 10
b = 20
c = 30
a, b, c = 10, 20, 30
# Ruby Bitwise Operators
a = 60
b = 13
# & Binary AND Operator copies a bit to the result if it exists in both operands.
a & b #=> 12
# | Binary OR Operator copies a bit if it exists in either operand.
a | b #=> 61
# ^ Binary XOR Operator copies the bit if it is set in one operand but not both.
a ^ b #=> 49
# ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
~a
# << Binary Left Shift Operator. The left operands value is moved
# left by the number of bits specified by the right operand.
a << 2
# >> Binary Right Shift Operator. The left operands value is moved
# right by the number of bits specified by the right operand.
a >> 2
# Ruby Logical Operators
a and b #=> true.
a or b #=> true.
a && b #=> true.
(a || b) #=> true.
!(a && b) #=> false.
not(a && b) #=> false.
# Ruby Ternary Operator
# ? :
# If Condition is true ? Then value X : Otherwise value Y
a == 10 ? puts 'Right' : puts 'Wrong'
# Ruby Range Operators
# .. Creates a range from start point to end point inclusive.
1..10 #=> Creates a range from 1 to 10 inclusive.
# ... Creates a range from start point to end point exclusive.
1...10 #=> Creates a range from 1 to 10 exclusive.
| Operators |
|---|
| !, ~, unary + |
| ** |
| unary - |
| *, /, % |
| +, - |
| <<, >> |
| & |
| ^ |
| >, >=, <, <= |
| <=>, ==, ===, !=, = |
| && |
| ?, : |
| modifier-rescue |
| =, +=, -=, *=, /=, %= |
| defined? |
| not |
| or, and |
| modifier-if, modifier-unless, modifier-while, modifier-until |
| { } blocks |
| do ... end blocks |
There are five different types of variables. The first character determines the scope.
| No | Name | Scope | Example | Note |
|---|---|---|---|---|
| 1 | [a-z] or _ | local | count = 10 or _count = 10 | Local variables must be initialized. |
| 2 | @ | instance variable | @id = [] | Instance variables have the nil value until they are initialized. |
| 3 | @@ | class variable | @@name = [] | Class variable must be initialized. |
| 4 | $ | global variable | $version = "0.8.9" | Global variables have the nil value until they are initialized. |
| 5 | [A-Z] | constant | PI = 3.14 | Constant variables must be initialized and you can change the constant but you will get a warning. |
Local variables are available to the block in which they are declared. A local variable declared within a loop or method cannot be accessed outside of that loop or method. They must either begin with an underscore or lowercase letter.
current_weather = "rainy"
_weather = "sunny"
Scope of a local variable is one of
Instance variable is specific instance of an object. Changes to an instance variable are only available to that instance of the object. Instance variables are declared with a single @ sign.
@current_weather = "rainy"
Scope of an instance variable is
Instance variables cannot be altered except for some methods, and it's distinct to each object of a class.
Class variables are shared by all instances of a Ruby class. If one object instance changes the value of a class variable, that new value will essentially change for all other object instances. Class variables begin with a double @ sign.
@@current_weather = "rainy"
Scope of a class variable is one of
It can be called from a class by calling ClassName.class_variable, and it's independent of any object of a class.
Global variables in Ruby are accessible anywhere in the Ruby program, regardless of where they are declared. Global variable names must begin with a dollar sign ($).
The use of global variables is discouraged because they are visible anywhere in the code for a program and can be changed from anywhere in a program. This can make tracking down bugs extremely difficult.
$current_weather = "rainy"
Scope of a global variable is
It can be referred from anywhere in a program.
Ruby constants are variables which, once assigned a value, shouldn't be changed. Constant declared outside of a class or module have global scope. If they are declared inside a class or module, they are available within the context of the class or module in which they were declared.
WEATHER = "rainy".freeze
Scope of a constant variable is
Accessible outside the class.
| No | Name | Note |
|---|---|---|
| 1 | self | The receiver object of the current method |
| 2 | true | Instance of the TrueClass |
| 3 | false | Instance of the FalseClass |
| 4 | nil | Instance of the NilClass |
| 5 | __FILE__ |
The name of current source file name |
| 6 | __LINE__ |
The current line number of the current source file |
| No | Name | Note |
|---|---|---|
| 1 | $! | The exception information message. raise sets this variable. |
| 2 | $@ | The backtrace of the last exception, which is the array of the String that indicates the point where methods invoked from. The elements in the format like: "filename:line" or "filename:line:in `methodname'" (Mnemonic: where exception occurred at.) |
| 3 | $& | The String matched by the last successful pattern match in this scope, or nil if the last pattern match failed. (Mnemonic: like & in some editors.) This variable is read-only. |
| 4 | $` | The String preceding whatever was matched by the last successful pattern match in the current scope, or nil if the last pattern match failed. (Mnemonic: ` often precedes a quoted string.) This variable is read-only. |
| 5 | $' | The String following whatever was matched by the last successful pattern match in the current scope, or nil if the last pattern match failed. (Mnemonic: ' often follows a quoted string.) |
| 6 | $+ | The last bracket matched by the last successful search pattern, or nil if the last pattern match failed. This is useful if you don't know which of a set of alternative patterns matched. (Mnemonic: be positive and forward looking.) |
| 7 | $1, $2... | Contains the subpattern from the corresponding set of parentheses in the last successful pattern matched, not counting patterns matched in nested blocks that have been exited already, or nil if the last pattern match failed. (Mnemonic: like \digit.) These variables are all read-only. |
| 8 | $~ | The information about the last match in the current scope. Setting this variables affects the match variables like $&, $+, $1, $2.. etc. The nth subexpression can be retrieved by $~[nth]. (Mnemonic: ~ is for match.) This variable is locally scoped. |
| 9 | $= | The flag for case insensitive, nil by default. (Mnemonic: = is for comparison.) |
| 10 | $/ | The input record separator, newline by default. Works like awk's RS variable. If it is set to nil, whole file will be read at once. (Mnemonic: / is used to delimit line boundaries when quoting poetry.) |
| 11 | $\ | The output record separator for the print and IO#write. The default is nil. (Mnemonic: It's just like /, but it's what you get "back" from Ruby.) |
| 12 | $, | The output field separator for the print. Also, it is the default separator for Array#join. (Mnemonic: what is printed when there is a , in your print statement.) |
| 13 | $; | The default separator for String#split. |
| 14 | $. | The current input line number of the last file that was read. |
| 15 | $< | The virtual concatenation file of the files given by command line arguments, or stdin (in case no argument file supplied). $<.file returns the current filename. (Mnemonic: $< is a shell input source.) |
| 16 | $> | The default output for print, printf. $stdout by default. (Mnemonic: $> is for shell output.) |
| 17 | $_ | The last input line of String by gets or readline. It is set to nil if gets/readline meet EOF. This variable is locally scoped. (Mnemonic: partly same as Perl.) |
| 17 | $0 | Contains the name of the file containing the Ruby script being executed. On some operating systems assigning to $0 modifies the argument area that the ps(1) program sees. This is more useful as a way of indicating the current program state than it is for hiding the program you're running. (Mnemonic: same as sh and ksh.) |
| 18 | $* | Command line arguments given for the script. The options for Ruby interpreter are already removed. (Mnemonic: same as sh and ksh.) |
| 19 | $$ | The process number of the Ruby running this script. (Mnemonic: same as shells.) |
| 20 | $? | The status of the last executed child process. |
| 21 | $: | The array contains the list of places to look for Ruby scripts and binary modules by load or require. It initially consists of the arguments to any -I command line switches, followed by the default Ruby library, probabl "/usr/local/lib/ruby", followed by ".", to represent the current directory. (Mnemonic: colon is the separators for PATH environment variable.) |
| 22 | $" | The array contains the module names loaded by require. Used for prevent require from load modules twice. (Mnemonic: prevent files to be doubly quoted(loaded).) |
| 23 | $DEBUG | The status of the -d switch. |
| 24 | $FILENAME | Same as $<.filename. |
| 25 | $LOAD_PATH | The alias to the $:. |
| 26 | $stdin | The current standard input. |
| 27 | $stdout | The current standard output. |
| 28 | $stderr | The current standard error output. |
| 29 | $VERBOSE | The verbose flag, which is set by the -v switch to the Ruby interpreter. |
The variables which names are in the form of $-?, where ? is the option character, are called option variables and contains the information about interpreter command line options.
| No | Name | Note |
|---|---|---|
| 1 | $-0 | The alias to the $/. |
| 2 | $-a | True if option -a is set. Read-only variable. |
| 3 | $-d | The alias to the $DEBUG. |
| 4 | $-F | The alias to the $;. |
| 5 | $-i | In in-place-edit mode, this variable holds the extention, otherwise nil. Can be assigned to enable (or disable) in-place-edit mode. |
| 6 | $-I | The alias to the $:. |
| 7 | $-l | True if option -lis set. Read-only variable. |
| 8 | $-p | True if option -pis set. Read-only variable. |
| 9 | $-v | The alias to the $VERBOSE. |
| No | Name | Note |
|---|---|---|
| 1 | TRUE | The typcal true value. All non-false values (everything except nil and false) is true in Ruby. |
| 2 | FALSE | The false itself. |
| 3 | NIL | The nil itself. |
| 4 | STDIN | The standard input. The default value for $stdin. |
| 5 | STDOUT | The standard output. The default value for $stdout. |
| 6 | STDERR | The standard error output. The default value for $stderr. |
| 7 | ENV | The hash-like object contains current environment variables. Setting a value in ENV changes the environment for child processes. |
| 8 | ARGF | The alias to the $<. |
| 9 | ARGV | The alias to the $*. |
| 10 | DATA | The file object of the script, pointing just after the END. Not defined unless the script is not read from the file. |
| 11 | VERSION | The Ruby version string. |
| 12 | RUBY_RELEASE_DATE | The relase date string. |
| 13 | RUBY_PLATFORM | The platform identifier. |
defined? count
"local-variable"
defined? @id
"instance-variable"
defined? @@name
"class variable"
defined? $version
"global-variable"
defined? PI
"constant"
num = 2
puts 'two' if num == 2
Executes code if the conditional is true.
temp = 19
if temp >= 25
puts "hot"
elsif temp < 25 && temp >= 18
puts "normal"
else
puts "cold"
end
# output
# normal
if expressions are used for conditional execution.
The values false and nil are false, and everything else are true.
Notice Ruby uses elsif, not else if nor elif.
Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed.
An if expression's conditional is separated from code by the reserved word then, a newline, or a semicolon.
# The unless is opposite of if, evaluates when the statement is false
name = "rob"
# if name != "bob"
unless name == "bob"
puts "hello stranger"
else
puts "hello bob"
end
# output
# hello stranger
num = 6
puts 'not two' unless num == 2
# output
# not two
Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed.
# case returns the value of the last expression executed
case input
# check an integer, 19
when 19
puts "It's 19"
# check a float number, 33.3
when 33.3
puts "It's 33.3"
# check an exact string, "Zaman"
when "Zaman"
puts "Hi Zaman"
when 10
puts "It's 10"
# check against a range
when 7..11
puts "It's between 7 and 11"
# check against multiple values, "coffee"
when "tea", "coffee"
puts "Happy days"
# check against a regular expression, "aA6"
when /^a[A-Z]+[0-6]+$/
puts "It's a valid match"
# check any string by comparing against the String class, "any string"
when String
puts "It's a String"
end
# using short syntax
case input
when 19 then puts "It's 19"
end
# optional fallthrough
case input
when 19 then puts "It's 19"
else
puts "It's not 19"
end
# get the return value
marks = 86
result = case marks
when 0..49 then "Fail"
when 50..64 then "Pass"
when 65..74 then "Credit"
when 75..84 then "Distinction"
when 85..100 then "High Distinction"
else "Invalid marks"
end
puts result
# High Distinction
Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches.
The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause.
A when statement's expression is separated from code by the reserved word then, a newline, or a semicolon.
Data types represent different types of data such as numbers, booleans, strings, etc. As an object-oriented language, all data types are based on classes.
| No | Type | Example | Class | Doc |
|---|---|---|---|---|
| 1 | Integer | a = 17 | a.class > Integer a.class.superclass > Numeric |
[link][2] |
| 2 | Float | a = 87.23 | a.class > Float a.class.superclass > Numeric |
[link][3] |
| 3 | String | a = "Hello universe" | a.class > String | [link][4] |
| 4 | Array | a = [12, 34] | a.class > Array | [link][5] |
| 5 | Hash | a = {type: "tea", count: 10} | a.class > Hash | [link][6] |
| 6 | Boolean | a = false a = true |
a.class > FalseClass a.class > TrueClass |
[TrueClass][7] [FalseClass][8] |
| 7 | Symbol | a = :status | a.class > Symbol | [link][9] |
| 8 | Nil | a = nil | a.class > NilClass | [link][11] |
In Ruby, Integer class is the basis for the two concrete classes that hold whole numbers. These concrete classes are Bignum and Fixnum. Fixnum holds integer values that are shown in the native machine word, whereas Bignum holds the integer value outside the range of Fixnum. Integer class contains a wide range of methods that are used for performing specified tasks. Integer class is a subclass of Numeric class.
Float objects represent inexact real numbers using the native architecture's double-precision floating point representation.
A string is a group of letters that represent a sentence or a word. Strings are defined by enclosing a text within a single (') or double (") quotes. You can use both double quotes and single quotes to create strings. Strings are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings doesn't allow substitution and allow backslash notation only for \ and \โ.
An array stores data or list of data. It can contain all types of data. Data in an array are separated by comma in between them and are enclosed within square bracket.The position of elements in an array starts with 0. A trailing comma is ignored.
A hash assign its values to its key. Value to a key is assigned by => sign. A key pair is separated with a comma between them and all the pairs are enclosed within curly braces. A hash in Ruby is like an object literal in JavaScript or an associative array in PHP. Theyโre made similarly to arrays. A trailing comma is ignored.
Boolean data type represents only one bit of information either true or false.
Symbols are light-weight strings. A symbol is preceded by a colon (:). They are used instead of strings because they can take up much less memory. Symbols have better performance.
# both are synonymous
a = 37
a.kind_of? Integer
# true
a.is_a? Integer
# true
Symbol objects represent names. Symbols are immutable, which means every symbol is unique, and we can't change it. Referencing the same symbol multiple times is the same as referencing the same object everywhere in your program. As a result, we can save both time and memory by referencing the same memory location. Symbols as hash keys.
week_days = {sunday: 11, monday: 222}
String interpolation allows you to combine strings together:
name = "World"
puts "Hello #{name}"
puts "The total is #{1+1}"
# "the total is 2"
A substring is a smaller part of a string, itโs useful if you only want that specific part, like the beginning, middle, or end.
string = "abc123"
string[0,3]
# "abc"
string[3,3]
# "123"
string[0..-2]
# "abc12"
#remove or replace the substring
string[0..2] = ""
puts string
# "123"
| No | Method name | Output |
|---|---|---|
| 1 | downcase | "HELLO World".downcase "hello world" |
| 2 | upcase | "hello worlD".upcase "HELLO WORLD" |
| 3 | capitalize | "hEllo wOrlD".capitalize "Hello world" |
| 4 | swapcase | "hEllo WOrlD".swapcase "HeLLO woRLd" |
| No | Method name | Output | Note |
|---|---|---|---|
| 1 | length or size | "HELLO World".length 11 "HELLO World".size 11 |
returns the length of the string |
| 2 | reverse | "hello worlD".reverse "Dlrow olleh" |
returns the reversed string |
| 3 | include? other_str | "hEllo wOrlD".include? "w" true |
returns true if the string or charecter is present or otherwise false |
| 4 | gsub(pattern, replacement) | "hEllo wOrlD".gsub(" ", "_") "hEllo_wOrlD" |
gsub or global substitute substitutes one or more string with provided strings |
| 5 | gsub(pattern, hash) | "organization".gsub("z", 'z' => 's') "organisation" |
gsub or global substitute substitutes one or more string with provided hash |
| 6 | gsub(pattern) { |match| block} | "Price of the phone is 1000 AUD".gsub(/\d+/) { |s| '$'+s } "Price of the phone is $1000 AUD" |
gsub or global substitute substitutes one or more string with provided block |
| 7 | strip | " hEllo WOrlD ".strip "hEllo WOrlD" |
It will remove (trim) any of the following leading and trailing characters: null("\x00"), horizontal tab("\t"), line feed(\n), vertical tab("\v"), form feed(f), carriage return(\r), space(" ") |
| 8 | prepend | a = "world" <br> a.prepend("hello ") "hello world" |
Add string before another string |
| 9 | insert | a = "hello" <br> a.insert(a.length, " world") "hello world" |
Insert string at a specific position |
| 10 | start_with? | string = "ruby programming" <br> string.start_with? "ruby" true |
To check if a string starts with a specific prefix |
| 11 | end_with? | string = "ruby programming" <br> string.end_with? "ruby" false |
To check if a string ends with a specific prefix |
| 12 | delete_suffix | string = "sausage is expensive" <br> string.delete_suffix(" is expensive") "sausage" |
Deletes suffix from a string |
| 13 | delete_prefix | string = "sausage is expensive" <br> string.delete_prefix("sausage") " is expensive" |
Deletes prefix from a string |
| 14 | split | string = "a b c d" <br> string.split ["a", "b", "c", "d"] |
Convert a String to An Array of Characters |
| 16 | join | arr = ['a', 'b', 'c'] <br> arr.join "abc" |
Convert an Array to a String |
| 17 | to_i | a = "49" <br> a.to_i 49 |
Convert a String Into An Integer |
| 18 | chop | "abcd?".chop("?") "abcd" |
Removes the Last Character From a String |
| 19 | count | str = "aaab" <br> str.count("a") 3 |
Counts character in a string |
| 20 | to_f | a = "49" <br> a.to_f 49.0 |
Convert a String Into A Floating Number |
| 21 | to_sym | a = "key" <br> a.to_sym :key |
Convert a String Into A Symbol |
| 22 | match | "abcd?".match(/ab/) #<MatchData "ab"> |
Convert pattern to regexp and invoke its match method on string |
| 23 | empty? | "hello".empty? false |
Return true if string has a length of zero |
| 24 | squeeze | "Booook".squeeze "Bok" |
Return copy of string where runs of the same character are replaced by a single character |
| 25 | * | puts "Ruby " * 4 Ruby Ruby Ruby Ruby |
Returns the concatenation of multiple copies of self |
| 26 | + | "sammy " + "shark" "sammyshark" |
Returns the concatenation of self and a given other string |
| 27 | eql? | s = 'foo' s.eql?('foo') true |
Returns true if object has the same length and content; as self; false otherwise |
| 26 | + | "sammy " + "shark" "sammyshark" |
Returns the concatenation of self and a given other string |
| 26 | + | "sammy " + "shark" "sammyshark" |
Returns the concatenation of self and a given other string |
2.even?
# true
3.even?
# false
65.chr
#=> "A"
36.gcdlcm(60)
#=> [12, 180]
36.lcm(60)
#=> 180
(-12345).abs
#=> 12345
1.next
#=> 2
(-1).succ
#=> 0
1.pred
#=> 0
5.remainder(3)
#=> 2
12345.to_s
#=> "12345"
12345.to_s(2)
#=> "11000000111001"
12345.to_s(8)
#=> "30071"
12345.to_s(10)
#=> "12345"
12345.to_s(16)
#=> "3039"
12345.to_s(36)
#=> "9ix"
12345.digits
#=> [5, 4, 3, 2, 1]
Ranges allow us to declare data with a beginning and an end, it has two operators to generate ranges.
# .. for creating inclusive ranges
range = 1..10
range.to_a
# output
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# ... for creating exclusive ranges
range = 1...10
range.to_a
# output
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
| No | Method name | Output |
|---|---|---|
| 1 | cover? | (1..5).cover?(5) true |
| 2 | end | ('a'..'z').end "z" |
| 3 | first | (1..5).first 1 |
| 4 | first(3) | ('A'..'Z').first(2) ["A", "B"] |
| 5 | eql? | ((0..2).eql?(0..5) false |
| 6 | begin | (1..10).begin #=> 1 |
| 7 | last | (10..20).last(3) #=> [18, 19, 20] |
| 8 | max | (10..20).max #=> 20 |
| 9 | min | (10..20).min #=> 10 |
(1..20).step(2) { |number| puts "#{number}"}
# output
# 1
# 3
# 5
# 7
# 9
# 11
# 13
# 15
# 17
# 19
A method is a function that takes zero or more parameters and returns a value. Ruby method returns nil by default.
Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly.
Methods should be defined before calling them, otherwise Ruby will raise an exception for undefined method invoking.
In Ruby, the last statement evaluated is the return value of that method. The return statement is optional. Depending on your preference, you can choose either of them ๐. I prefer to use the return statement because it's easier to understand.
def method_name(parameter1, parameter2)
puts "#{parameter1} #{parameter2}"
parameter1 + parameter2
end
res = method_name(20, 10)
# output
# 30
def method_name(parameter1, parameter2)
puts "#{parameter1} #{parameter2}"
return parameter1 + parameter2
end
# output
# 30
res = method_name(parameter1, parameter2)
# In Ruby you can call methods without parentheses
res = method_name parameter1, parameter2
The most important drawback to using methods with parameters is that you need to remember the number of parameters whenever you call such methods. For example, if a method accepts three parameters and you pass only two, then Ruby displays an error.
def method_name(parameter1, parameter2, type = "ADD")
puts "#{parameter1} #{parameter2}"
return parameter1 + parameter2 if type == "ADD"
return parameter1 - parameter2 if type == "SUB"
end
res = method_name(20, 10)
# output
# 30
def method_name(num1, num2 = num1)
return num1 + num2
end
res = method_name(10)
# output
# 20
def method_name(type, *values)
return values.reduce(:+) if type == "ADD"
return values.reduce(:-) if type == "SUB"
end
numbers = [2, 2, 2, 3, 3, 3]
res = method_name("ADD", *numbers)
# output
# 15
res = method_name("SUB", *numbers)
# output
# -11
# or you can provide the values like this
res = method_name("ADD", 2, 2, 2, 3, 3, 3)
# output
# 15
The ! is used after the method when you want to modify the object.
a = ["Drama",
"Mystery",
"Crime",
"Sci-fi",
"Disaster",
"Thriller"]
a.sort
puts a
# we didn't modify the object
# Drama
# Mystery
# Crime
# Sci-fi
# Disaster
# Thriller
a.sort!
puts a
# modify the object
# Crime
# Disaster
# Drama
# Mystery
# Sci-fi
# Thriller
In ruby methods that end with a question mark (?) are called boolean methods, which either returns true or false.
"some text".nil?
# false
nil.nil?
# true
You can have your own boolean methods.
def is_vowel?(char)
['a','e','i','o','u'].include? char
end
is_vowel? 'a'
# true
is_vowel? 'b'
# false
A class method is a class-level method. There are multiple ways of defining a class method.
When a method is defined outside of the class definition, the method is marked as private by default. On the other hand, the methods defined in the class definition are marked as public by default. The default visibility and the private mark of the methods can be changed by public or private of the Module.
Whenever you want to access a method of a class, you first need to instantiate the class. Then, using the object, you can access any member of the class.
Ruby gives you a way to access a method without instantiating a class. Let us see how a class method is declared and accessed โ
class Mobile
def self.ring
"ring ring ring..."
end
end
Mobile.ring
class Mobile
def Mobile.ring
"ring ring ring..."
end
end
Mobile.ring
class Mobile
class << self
def ring
"ring ring ring..."
end
end
end
Mobile.ring
To access this method, you need not create objects of the class Mobile.
A class method is an instance method of the class object. When a new class is created, an object of type Class is
initialized and assigned to a global constant (Mobile in this case).
Mobile = Class.new do
def self.ring
"ring ring ring..."
end
end
Mobile.ring
Mobile = Class.new
class << Mobile
def ring
"ring ring ring..."
end
end
Mobile.ring
In Ruby, a block is a piece of code that can be passed as an argument to a method, and is executed by the method at a later time. Blocks are defined using the keywords "do" and "end" or using curly braces {}. They can also be passed using the "yield" keyword within a method. They are commonly used in iterators such as "each" and "map" to perform an operation on each element of a collection. A block returns the last evaluated statement.
Blocks in Ruby have a few key aspects that are significant:
# return value
def give_me_data
data = yield
puts "data = #{data}"
end
give_me_data { "Big data" }
# output
# data = Big data
# single line block
salary = [399, 234, 566, 533, 233]
salary.each { |s| puts s }
# puts s = block body
# |s| = block arugments
# multiline block
salary.each do |s|
a = 10
res = a * s
puts res
end
# block body
# a = 10
# res = a * s
# puts res
# block arugments
# |s|
Methods can take blocks implicitly and explicitly. If you want to call a block implicitly use the yield keyword.
Yield finds the block and calls the passed block. Since you can pass implicit blocks, you don't have to call yield, and the block will be ignored.
# passing a block implicitly
def give_me_data
puts "I am inside give_me_data method"
yield
puts "I am back in give_me_data method"
end
give_me_data { puts "Big data" }
# output
# I am inside give_me_data method
# Big data
# I am back in give_me_data method
# call multiple times
def give_me_data
yield
yield
yield
end
give_me_data { puts "Big data" }
# output
# Big data
# Big data
# Big data
# call with block arguments
def give_me_data
yield 10
yield 100
yield 30
end
give_me_data { |data| puts "Big data #{data} TB" }
# output
# Big data 10 TB
# Big data 100 TB
# Big data 30 TB
# call with multiple block arguments
def give_me_data
yield "Big data", 10, "TB"
yield "Big data", 100, "GB"
yield "Big data", 30, "MB"
end
give_me_data { |text, data, unit| puts "#{text} #{data} #{unit}" }
# output
# Big data 10 TB
# Big data 100 GB
# Big data 30 MB
# block will try to return from the current context
give_me_data
puts "I am inside give_me_data method"
end
def test
puts "I am inside test method"
give_me_data { return 10 } # code returns from here
puts "I am back in test method"
end
return_value = test
# output
# I am inside test method
# I am inside give_me_data method
# 10
# passing a block explicitly by using an ampersand parameter, here we are explicitly defining the method with block parameter and calling it
def give_me_data(&block)
block.call
block.call
end
give_me_data { puts "Big data" }
# output
# Big data
# Big data
Block parameter is mandatory when you call yield inside a method; otherwise, it will raise an exception
def give_me_data
yield
end
give_me_data
# output
# LocalJumpError: no block given (yield)
# you can use block_given? method to handle the exception and make the block optional
def give_me_data
return "no block" unless block_given?
yield
end
give_me_data { puts "Big data" }
give_me_data
# output
# Big data
def give_me_data(&block)
block.call if block
end
give_me_data { puts "Big data" }
give_me_data
# output
# Big data
In Ruby, a proc (short for "procedure") is a way to package a block of code as an object, which can be passed around and reused like any other object in Ruby. This allows you to define a block of code once and use it in multiple places, rather than having to repeat the same code multiple times.
The benefits of using Procs include:
Procs can be created by passing a block to the Proc.new or lambda methods, or by using
the shorthand notation: my_proc = proc {puts "Hello, World!"} and my_proc.call can be used to invoke the proc
p = Proc.new { puts "Hello World" }
def give_me_data(proc)
proc.call
end
give_me_data p
# output
# Hello World
# arbitrary arguments
p = Proc.new { |count| "Hello World " * count }
def give_me_data(proc)
proc.call 5, 2
end
give_me_data p
# output
# "Hello World Hello World Hello World Hello World Hello World "
# proc will try to return from the current context
p = Proc.new { return 10 }
p.call
# output
LocalJumpError: unexpected return
# because you canโt return from the top-level context
def give_me_data
puts "I am inside give_me_data method"
p = Proc.new { return 10 }
p.call # code returns from here
puts "I am back in give_me_data method"
end
return_value = give_me_data
puts return_value
# output
# I am inside give_me_data method
# 10
Lambdas are a powerful feature of the Ruby language. They allow you to wrap logic and data into a portable package. A lambda function encapsulates control flow, parameters and local variables into a single package assigned to a variable or used inline. If assigned to a variable, it can be passed to other functions or stored in data structures, just like a more typical variable containing a string or float.
A lambda function can then be executed far from the code location where it was defined. Lambda functions are often
called anonymous functions or a function literal, wrap the lambda with do and end (for multiline) or curly brackets
{ and } (for a single line). Lambda returns the last evaluated statement.
With Ruby, the lambda keyword is used to create a lambda function. It requires a block and can define zero or more parameters. You call the resulting lambda function by using the call method.
The following are specific situations in which you might want to use a Ruby lambda.
In Ruby, a lambda is a type of Proc that has some specific characteristics and behaviors. Like a Proc, a lambda is a way to package a block of code as a object that can be passed around and reused, but there are some differences between the two.
The main difference between a lambda and a proc is in the way they handle the "return" keyword. In a proc, the "return" keyword will return from the method that the proc was defined in, whereas in a lambda, the "return" keyword will only return from the lambda itself.
The benefits of using a lambda include:
lifeparticle/Ruby-Cheatsheet is a public repo on GitHub by lifeparticle. ๐ The Missing Cheatsheet for Ruby.
It declares the MIT license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-10-31. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
A list of useful payloads and bypass for Web Application Security and Pentest/CTF
An updated version of the classic "Basic Computer Games" book, with well-written examples in a variety of common MEMORY SAFE, SCRIPTING programming languages. See https://coding-horror.github.io/basic-computer-games/

Master programming by recreating your favorite technologies from scratch.
:globe_with_meridians: Jekyll is a blog-aware static site generator in Ruby
๐ The Ultimate Markdown Cheatsheet


โ๏ธ Bangla Alphabet (เฆฌเฆพเฆเฆฒเฆพ เฆฌเฆฐเงเฆฃเฆฎเฆพเฆฒเฆพ)
๐ฐ We Provide an Array of Developer Productivity Tools Designed To Help You Save Time
The missing Cheatsheet for Python
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/lifeparticle/Ruby-CheatsheetTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.