Ruby code snippets with use cases
30 ready-made code building blocks, sorted by topic.
Basics
- Hello World – A first test of whether Ruby is installed correctly.
- Variables and Types – Store values and check their type with .class.
- Handling nil Safely (&. and ||=) – Read optional values from hashes or API responses without crashing on nil.
Control flow
- if / elsif / else – React differently, e.g. for grades, price tiers or access rights.
- Loops with times and each – Process every element of a list or repeat n times.
- case / when with Ranges and Classes – Classify input, e.g. age groups, file types or HTTP status codes.
Functions
- Method with Keyword Argument – Bundle recurring logic, e.g. greeting texts or calculations.
- Your Own Method with a Block (yield) – Encapsulate recurring framing logic, e.g. timing, logging or cleanup.
- Lambda, Proc and &:symbol – Store and pass on behavior, e.g. filters, discount rules or callbacks.
Data structures
- Working with Arrays – Manage collections of values: add, sort, filter, convert.
- Hash (Dictionary) – Store mappings, e.g. configurations or JSON-like data.
- Counting with Hash.new(0) and tally – Determine frequencies, e.g. words in a text or status values in logs.
- Sorting and Extreme Values – Order records by a field, e.g. users by age or products by price.
- Enumerable Pipeline – Filter, transform and summarize data in a few steps, e.g. order totals or log analysis.
- group_by and partition – Split records by category, e.g. orders per customer or valid/invalid input.
OOP
- Class with Inheritance – Bundle data and behavior, e.g. users, products or game characters.
- Struct as a Quick Data Class – Small data objects without much code, e.g. coordinates, CSV rows or return values.
- Data.define (Immutable) – Value objects like money, coordinates or DTOs that must never change.
- Mixin with Enumerable and Comparable – Make your own collections or values sortable and searchable without writing everything…
Advanced
- Pattern Matching with case/in – Evaluate JSON responses or messages of different shapes.
- method_missing and define_method – Build flexible APIs and DSLs, e.g. dynamic finders or configuration objects.
- Lazy Enumerator – Process huge or infinite sequences without holding everything in memory (e.g. large log…
More snippets
- begin / rescue / ensure – Guard user input or network access without the program crashing.
- Custom Error Class with retry – Name domain errors unambiguously and repeat flaky calls (network).
- Write and Read a File – Save logs, configurations or text data and load them again.
- Reading and Writing JSON – Exchange data with web APIs or other programs, read configuration files.
- Editing and Formatting Strings – Clean up input, reshape texts and print prices or tables.
- HTTP Request with Net::HTTP – Fetch data from a web API, e.g. weather, GitHub or payment services.
- Gemfile with Groups – Define the dependencies of a project reproducibly (web, tests, development).
- Rails: Model with Validation – Map database tables as classes – including rules and associations.