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 objekt | Output: with line break / without / debug representation |
name = "Ada" | Create a variable (no keyword, no type) |
MWST = 0.19 | Constant (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_sym | Conversions |
Integer("42") Float("3.5") | Strict conversion (raises ArgumentError) |
# comment | Single-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 not | Logical operators (prefer &&, ||, !) |
a ||= 5 | Assign only if a is nil/false |
obj&.methode | Safe 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 ... end | Branching (elsif without an e) |
puts "x" if bedingung puts "y" unless bedingung | Modifier form / negated condition |
case x
when 1..5 then "a"
else "b"
end | case/when (uses ===: values, ranges, classes, regex) |
case data
in { name: String => n } then n
end | Pattern matching (since Ruby 3.0) |
5.times { |i| ... } 1.upto(3) { ... } | Repeat |
while cond ... end until cond ... end loop do ... end | Condition-based loops |
break next redo | Abort loop / next round / repeat round |
Strings & Symbols
s.upcase s.downcase s.capitalize s.swapcase | Upper/lower case |
s.strip s.lstrip s.rstrip s.chomp | Remove 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.length | Character, substring, length |
format("%05.2f %s %d", 3.14159, "x", 7) "%.2f" % 3.14159 | Formatting |
s =~ /\d+/ s.match?(/\d+/) s.scan(/\w+/) | Regex: position / check for a match / all matches |
<<~TEXT
mehrzeilig
TEXT | Heredoc (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.compact | Sort, reverse, remove duplicates/nil |
a.include?(2) a.index(2) a.empty? | Search / check |
a + b a - b a & b a | b | Concatenate / difference / intersection / union |
a.flatten a.zip(b) a.rotate a.sample a.shuffle | Flatten, pair up, rotate, random |
x, *rest = a | Destructuring 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.size | Keys, 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_map | Transform (also nested / with filter) |
select { } reject { } find { } find_all | Filter / find |
reduce(:+) inject(1) { |a, b| a * b } sum | Combine |
count min max minmax min_by max_by sum | Count and extreme values |
group_by { } partition { } tally chunk_while | Group, 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 * x | Endless 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 ... end | Class with inheritance (only one parent class) |
def initialize(x)
@x = x
end | Constructor with an instance variable |
attr_reader :x attr_writer :x attr_accessor :x | Create getter / setter / both |
def self.methode ... end @@zaehler | Class method / class variable |
private protected public | Visibility (applies to the following methods) |
module M ... end include M extend M prepend M | Define a module and mix it in |
include Comparable include Enumerable | Only 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 ... end | Error handling |
raise ArgumentError, "Text" raise "Text" | Raise an error |
retry | Run the begin block again (inside rescue) |
class MeinFehler < StandardError; end | Custom 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 irb | Run a script / interactive shell |
ruby -e 'puts 1 + 2' | One-liner in the terminal |
gem install name gem list | Install / show gems |
bundle init bundle add name bundle install | Bundler: create Gemfile / add a gem / install |
bundle exec ruby app.rb | Run 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 server | Rails: project, console, server |
rake -T rubocop | Show Rake tasks / check style |