RbRuby

Ruby cheatsheet – syntax overview

94 key commands and patterns for quick reference.

Basics Operators Control flow Strings & Symbols Arrays Hashes Enumerable Methods & Blocks Classes, Modules & Struct Errors & Files Gems, Bundler & Tools

Basics

puts "Text" print "Text" p objektOutput: with line break / without / debug representation
name = "Ada"Create a variable (no keyword, no type)
MWST = 0.19Constant (uppercase)
"Hello #{name}!"String interpolation (only in double quotes)
x.class x.is_a?(Integer) x.nil?Determine / check the type
"42".to_i "3.5".to_f 42.to_s :a.to_s "a".to_symConversions
Integer("42") Float("3.5")Strict conversion (raises ArgumentError)
# commentSingle-line comment

Operators

+ - * / % **Arithmetic (integer division with two integers!)
7.fdiv(2) 7.divmod(2)Floating-point division / [quotient, remainder]
== != < > <= >= <=>Comparisons; <=> returns -1, 0, 1
&& || ! and or notLogical operators (prefer &&, ||, !)
a ||= 5Assign only if a is nil/false
obj&.methodeSafe navigation: nil instead of NoMethodError
1..5 1...5 ("a".."e")Ranges (inclusive / exclusive end)
a.equal?(b) a.eql?(b)Identity / value-and-type equality

Control flow

if x > 0 ... elsif x == 0 ... else ... endBranching (elsif without an e)
puts "x" if bedingung puts "y" unless bedingungModifier form / negated condition
case x when 1..5 then "a" else "b" endcase/when (uses ===: values, ranges, classes, regex)
case data in { name: String => n } then n endPattern matching (since Ruby 3.0)
5.times { |i| ... } 1.upto(3) { ... }Repeat
while cond ... end until cond ... end loop do ... endCondition-based loops
break next redoAbort loop / next round / repeat round

Strings & Symbols

s.upcase s.downcase s.capitalize s.swapcaseUpper/lower case
s.strip s.lstrip s.rstrip s.chompRemove whitespace / line break
s.split(",") liste.join(",")Split / join
s.sub("a", "b") s.gsub(/x/, "y")Replace first / all occurrences
s.include?("x") s.start_with?("x") s.end_with?("x")Contains / starts with / ends with
s[0] s[1..3] s[-1] s.lengthCharacter, substring, length
format("%05.2f %s %d", 3.14159, "x", 7) "%.2f" % 3.14159Formatting
s =~ /\d+/ s.match?(/\d+/) s.scan(/\w+/)Regex: position / check for a match / all matches
<<~TEXT mehrzeilig TEXTHeredoc (with indentation removed)
s.freeze s.frozen? +"text"Freeze / check / mutable copy

Arrays

a = [1, 2, 3] %w[x y z]Create an array (word list)
a << 4 a.push(5) a.unshift(0)Append to the end / to the front
a.pop a.shift a.delete(2) a.delete_at(0)Remove
a.first a.last a[-2] a[1..2] a.first(2)Access
a.sort a.sort! a.reverse a.uniq a.compactSort, reverse, remove duplicates/nil
a.include?(2) a.index(2) a.empty?Search / check
a + b a - b a & b a | bConcatenate / difference / intersection / union
a.flatten a.zip(b) a.rotate a.sample a.shuffleFlatten, pair up, rotate, random
x, *rest = aDestructuring with splat

Hashes

h = { name: "Ada", "k" => 1 }Create a hash (symbol keys and arbitrary keys)
h[:name] h.fetch(:x, 0) h.dig(:a, :b)Read: nil / default value / nested
h[:neu] = 1 h.delete(:name) h.merge(h2)Set, delete, merge
h.keys h.values h.key?(:x) h.sizeKeys, values, check, count
h.each { |k, v| ... } h.map { |k, v| ... }Iterate
h.select { |k, v| v > 1 } h.transform_values(&:to_s)Filter / transform values
Hash.new(0) Hash.new { |h, k| h[k] = [] }Default value / default via block
h.to_a h.sort_by { |k, v| v } h.min_by { |k, v| v }Convert, sort, minimum

Enumerable

map { |x| x * 2 } flat_map filter_mapTransform (also nested / with filter)
select { } reject { } find { } find_allFilter / find
reduce(:+) inject(1) { |a, b| a * b } sumCombine
count min max minmax min_by max_by sumCount and extreme values
group_by { } partition { } tally chunk_whileGroup, split, count
each_with_index each_with_object({}) each_slice(2) each_cons(2)Iterate with extra info / in chunks
any? { } all? { } none? { } one? { }Checks
sort_by { |x| x.name } take(3) drop(2) take_while { }Sort, take parts
lazy.select { }.map { }.first(3)Lazy evaluation for large sequences

Methods & Blocks

def f(a, b = 2, *rest, k:, o: 1, **opts, &blk)All kinds of parameters (mind the order)
def quadrat(x) = x * xEndless method (since Ruby 3.0)
yield x block_given?Call the block / check whether one was passed
->(x) { x * 2 } proc { |x| x * 2 }Lambda / Proc
f.call(1) f.(1) f[1]Call a lambda (three notations)
liste.map(&:upcase) liste.each(&methode)Pass a symbol/Proc as a block
empty? even? save!Convention: ? = boolean, ! = "dangerous"
obj.send(:name, arg) obj.respond_to?(:name)Call a method by name / check

Classes, Modules & Struct

class A < B ... endClass with inheritance (only one parent class)
def initialize(x) @x = x endConstructor with an instance variable
attr_reader :x attr_writer :x attr_accessor :xCreate getter / setter / both
def self.methode ... end @@zaehlerClass method / class variable
private protected publicVisibility (applies to the following methods)
module M ... end include M extend M prepend MDefine a module and mix it in
include Comparable include EnumerableOnly needs <=> or each
P = Struct.new(:x, :y)Quick data class
K = Data.define(:lat, :lon) k.with(lat: 1)Immutable data class (Ruby 3.2)
super super(a, b)Call the method of the parent class

Errors & Files

begin ... rescue A => e ... else ... ensure ... endError handling
raise ArgumentError, "Text" raise "Text"Raise an error
retryRun the begin block again (inside rescue)
class MeinFehler < StandardError; endCustom error class
File.read(p) File.write(p, s) File.readlines(p, chomp: true)Read / write a file / lines
File.open(p, "a") { |f| f.puts "x" }File with a block (closed automatically)
File.foreach(p) { |zeile| ... }Read line by line (memory-friendly)
File.exist?(p) Dir.glob("*.rb") File.basename(p)Check / list / name
require "json"; JSON.parse(s); JSON.generate(h)JSON (standard library)

Gems, Bundler & Tools

ruby datei.rb irbRun a script / interactive shell
ruby -e 'puts 1 + 2'One-liner in the terminal
gem install name gem listInstall / show gems
bundle init bundle add name bundle installBundler: create Gemfile / add a gem / install
bundle exec ruby app.rbRun with the versions from Gemfile.lock
require "set" require_relative "hilfe"Load a gem/standard library / load your own file
rails new app bin/rails console bin/rails serverRails: project, console, server
rake -T rubocopShow Rake tasks / check style