{"id":1184,"date":"2026-09-02T15:37:58","date_gmt":"2026-09-02T14:37:58","guid":{"rendered":"https:\/\/ruby-doc.org\/learn\/?p=1184"},"modified":"2026-09-03T14:56:54","modified_gmt":"2026-09-03T13:56:54","slug":"ruby-code-examples","status":"publish","type":"post","link":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/","title":{"rendered":"Ruby Code Examples: 20 Practical Snippets for Beginners"},"content":{"rendered":"\n<p class=\"article-attribution wp-block-paragraph\"><strong>Written by <a href=\"https:\/\/ruby-doc.org\/learn\/james-britt\/\">James Britt<\/a><\/strong><br>Technically reviewed by <a href=\"https:\/\/ruby-doc.org\/learn\/jim-freeze\/\">Jim Freeze<\/a> \u00b7 Reviewed 3 September 2026<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you learn best by taking working code apart, this collection of Ruby code examples is designed for you. It starts with small expressions, then moves through collections, methods, classes, files, JSON, regular expressions, and a complete mini-project. Every snippet is self-contained. Copy one into a file such as example.rb , then run it from a terminal with ruby example.rb . Change the values and run it again: experimentation is usually the quickest way to make Ruby&#8217;s concise syntax feel natural.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Ruby Code Examples at a Glance<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#output-variables\">Output, variables, and interpolation<\/a><\/li>\n\n\n\n<li><a href=\"#arrays-hashes-ranges\">Arrays, hashes, and ranges<\/a><\/li>\n\n\n\n<li><a href=\"#conditions-loops\">Conditions and loops<\/a><\/li>\n\n\n\n<li><a href=\"#mapping-filtering-reducing\">Mapping, filtering, and reducing<\/a><\/li>\n\n\n\n<li><a href=\"#methods-classes-modules\">Methods, classes, and modules<\/a><\/li>\n\n\n\n<li><a href=\"#errors-files-json-regex\">Errors, files, JSON, and regular expressions<\/a><\/li>\n\n\n\n<li><a href=\"#mini-project\">A complete word-frequency program<\/a><\/li>\n<\/ul>\n\n\n\n<h2 id=\"output-variables\" class=\"wp-block-heading\">1. Print Text and Store a Value<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">puts prints a value followed by a newline. Ruby variables do not need a type declaration; the object assigned to the name determines what operations are available. The #{&#8230;} sections are string interpolation. Ruby evaluates each expression and inserts its result into a double-quoted string. Single-quoted strings do not interpolate values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>language = \"Ruby\"\nyear = 1995\n\nputs \"Learning #{language}\"\nputs \"Ruby first appeared in #{year}.\"\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">2. Work With Numbers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In addition to being able to use common mathematical operations in your code, Ruby also has some rules that govern how they work. When dividing one number by another, if both numbers are integers then the result is an integer. So, you will need to include a decimal value for a result with decimals. The underscore character may be used to make large values easier to read: for example, 1_000_000 and 1000000 have the same value. Try this using whole-number values and decimal values to see how each operand&#8217;s data type determines the result of division.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>subtotal = 24.50\nquantity = 3\ndiscount = 5\n\ntotal = (subtotal * quantity) - discount\naverage = total \/ quantity\n\nputs total.round(2)   # 68.5\nputs average.round(2) # 22.83\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">3. Transform a String<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Strings have standard methods for normal cleanup and formatting. This example has strip remove any leading or trailing white space, split create a list of individual words, map apply capitalize to each word, and join reconstruct the last string. When something doesn&#8217;t behave as expected with a chain, either print its value during execution or inspect the intermediate results. It is common, when things don&#8217;t seem to be working correctly, to look at what was produced by split before proceeding.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>raw_title = \"  ruby code examples  \"\n\nclean_title = raw_title.strip.split.map(&amp;:capitalize).join(\" \")\n\nputs clean_title # Ruby Code Examples\n<\/code><\/pre>\n\n\n\n<h2 id=\"arrays-hashes-ranges\" class=\"wp-block-heading\">4. Add, Remove, and Read Array Items<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/www.cs.fsu.edu\/~myers\/c++\/notes\/arrays.html\">An array is an ordered collection<\/a>. Indexes begin at zero, while a negative index counts backwards from the end. The shovel operator, &lt;&lt; , appends an item to the array. Methods such as first , last , include? , and length make routine checks readable. Test the array with duplicate names and with no items at all. Notice that delete changes the existing array, while reader methods simply return information about its current contents.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>frameworks = &#91;\"Rails\", \"Sinatra\"]\n\nframeworks &lt;&lt; \"Hanami\"\nframeworks.delete(\"Sinatra\")\n\nputs frameworks.first # Rails\nputs frameworks&#91;-1]   # Hanami\nputs frameworks.length # 2\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">5. Store Named Values in a Hash<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Hashes hold values by key. The key can be one of several types of object in Ruby; symbols are simply a common type used as names within the code. Using square brackets retrieves the value for an existing key or assigns a new value. When iterating, a two-parameter block receives the current key and its associated value. Compare how a lookup of a non-existent key returns nil with how fetch can return a default you provide. Depending on what should happen when an entry is missing, either behaviour may serve well.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>book = {\n  title: \"The Ruby Way\",\n  pages: 816,\n  available: true\n}\n\nputs book&#91;:title]\nbook&#91;:pages] = 820\nbook&#91;:format] = \"paperback\"\n\nbook.each do |key, value|\n  puts \"#{key}: #{value}\"\nend\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">6. Generate Values From a Range<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Two dots are used to define an inclusive range. Three dots define a range where the final value is excluded. Ranges can represent sequences, select slices, or test whether a value falls between two endpoints. When defining one, it is easy to make an off-by-one error by choosing the wrong form for the problem being solved.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>inclusive = (1..5).to_a\nexclusive = (1...5).to_a\n\nputs inclusive.inspect # &#91;1, 2, 3, 4, 5]\nputs exclusive.inspect # &#91;1, 2, 3, 4]\nputs (1..10).include?(7) # true\n<\/code><\/pre>\n\n\n\n<h2 id=\"conditions-loops\" class=\"wp-block-heading\">7. Make a Decision With if, elsif, and else<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Ruby treats only false and nil as falsey. Everything else, including 0 and an empty string, is truthy. A short condition can also follow the action: puts &#8220;Take a coat&#8221; if temperature &lt; 10 . Run the condition with values on either side of every boundary. Testing the exact cutoff as well as nearby values is a simple habit that catches faulty comparison operators early.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>temperature = 18\n\nif temperature &gt;= 25\n  puts \"Warm\"\nelsif temperature &gt;= 15\n  puts \"Mild\"\nelse\n  puts \"Cool\"\nend\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">8. Match Several Possibilities With case<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A case expression generally reads better than many equality checks chained in succession; it also allows for direct assignment of the result. Because Ruby employs case-equality behaviour rather than simply comparing values on a branch-by-branch basis, range branches can keep related status codes together while still allowing an individual branch when you need a unique message for one status.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>status_code = 404\n\nmessage = case status_code\n          when 200..299 then \"Success\"\n          when 400      then \"Bad request\"\n          when 404      then \"Not found\"\n          when 500..599 then \"Server error\"\n          else \"Unknown status\"\n          end\n\nputs message\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">9. Loop With each and each_with_index<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Ruby programs usually iterate over a collection instead of maintaining a counter manually. The block between do and end runs once per item. each_with_index supplies both the item and its zero-based position. Remove the index adjustment and compare the output. The collection position begins at zero, but numbered text intended for readers will usually begin at one.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>topics = &#91;\"strings\", \"arrays\", \"hashes\"]\n\ntopics.each_with_index do |topic, index|\n  puts \"#{index + 1}. #{topic.capitalize}\"\nend\n<\/code><\/pre>\n\n\n\n<h2 id=\"mapping-filtering-reducing\" class=\"wp-block-heading\">10. Build a New Array With map<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Use map when all input items will be used to create one output item. Map creates an entirely new collection. As you see in the example, prices_with_vat is a variable and not a method. After assigning prices_with_vat, the old prices remain unchanged in the original array. This is because the returned list of numbers from map was created as a new array through a separate assignment.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>prices = &#91;8.00, 12.50, 20.00]\n\nprices_with_vat = prices.map do |price|\n  (price * 1.20).round(2)\nend\n\np prices_with_vat # &#91;9.6, 15.0, 24.0]\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">11. Filter Items With select and reject<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">select keeps items for which the block is truthy. reject does the opposite. Replace even? with another predicate and watch which values survive. Thinking of select as &#8216;keep matching items&#8217; and reject as &#8216;discard matching items&#8217; makes the pair easier to remember. Work slowly enough to connect the output with the specific expression that produced it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;3, 8, 11, 14, 19, 22]\n\neven_numbers = numbers.select(&amp;:even?)\nsmall_numbers = numbers.reject { |number| number &gt;= 10 }\n\np even_numbers  # &#91;8, 14, 22]\np small_numbers # &#91;3, 8]\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">12. Combine Values With reduce<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">reduce , also known as inject , carries an accumulated value through the collection. It is handy for totals and other single-result calculations. Change the starting accumulator and follow the sum after each iteration. The initial value matters because it becomes the first left-hand input supplied to the block. Work slowly enough to connect the output with the specific expression that produced it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>basket = { keyboard: 45.00, mouse: 20.00, cable: 6.50 }\n\ntotal = basket.values.reduce(0) do |sum, price|\n  sum + price\nend\n\nputs format(\"\u00a3%.2f\", total) # \u00a371.50\n<\/code><\/pre>\n\n\n\n<h2 id=\"methods-classes-modules\" class=\"wp-block-heading\">13. Define a Method With Keyword Arguments<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Methods package behaviour behind a useful name. Keyword arguments make calls easier to understand and allow defaults for optional settings. Ruby returns the last evaluated expression automatically, so an explicit return is unnecessary here. Call the method with keyword arguments in a different order. Their names, rather than their positions, identify the values, which makes a call with several options much easier to read.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def greeting(name:, formal: false)\n  formal ? \"Good morning, #{name}.\" : \"Hi, #{name}!\"\nend\n\nputs greeting(name: \"Mina\")\nputs greeting(name: \"Mina\", formal: true)\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">14. Handle a Missing Value Safely<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The safe-navigation operator, &amp;. , calls a method when the receiver is not nil . If it is nil , the expression returns nil instead of raising NoMethodError . Use safe navigation deliberately. If a missing object indicates a programming error, allowing an exception may be more useful than silently substituting a fallback.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>user = { profile: nil }\n\nname = user&#91;:profile]&amp;.fetch(:name, nil) || \"Guest\"\n\nputs name # Guest\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">15. Create a Class<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A class groups state and behaviour. The initialize method runs when new creates an instance, and attr_reader generates getter methods. Names beginning with @ are instance variables. Each BankAccount object keeps its own values. Attempt a negative deposit and read the resulting exception. Validation inside the object protects its state, regardless of which part of the program calls the method.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class BankAccount\n  attr_reader :owner, :balance\n\n  def initialize(owner, opening_balance = 0)\n    @owner = owner\n    @balance = opening_balance\n  end\n\n  def deposit(amount)\n    raise ArgumentError, \"Amount must be positive\" unless amount.positive?\n\n    @balance += amount\n  end\nend\n\naccount = BankAccount.new(\"Ari\", 100)\naccount.deposit(25)\n\nputs account.balance # 125\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">16. Share Behaviour With a Module<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A module can act as a namespace or provide reusable behaviour. Including it in a class adds its instance methods to objects of that class. Give the article name punctuation and repeated spaces. The module keeps slug-building behaviour in one place, ready for another class that exposes the same name method.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>module Sluggable\n  def slug\n    name.downcase.strip.gsub(\/&#91;^a-z0-9]+\/, \"-\").gsub(\/^-|-$\/, \"\")\n  end\nend\n\nclass Article\n  include Sluggable\n  attr_reader :name\n\n  def initialize(name)\n    @name = name\n  end\nend\n\narticle = Article.new(\"20 Useful Ruby Examples\")\nputs article.slug # 20-useful-ruby-examples\n<\/code><\/pre>\n\n\n\n<h2 id=\"errors-files-json-regex\" class=\"wp-block-heading\">17. Rescue an Expected Exception<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Rescue errors you know how to handle. Avoid catching every possible exception without a clear recovery path, because that can hide genuine bugs. Integer is preferable to to_i when invalid input must be detected: &#8220;hello&#8221;.to_i quietly returns zero, while Integer(&#8220;hello&#8221;) raises ArgumentError . Compare a valid zero with a word that cannot be converted. Returning nil for the latter lets the caller distinguish bad input from the perfectly legitimate number zero.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def integer_from(text)\n  Integer(text, 10)\nrescue ArgumentError\n  nil\nend\n\nvalue = integer_from(\"42\")\ninvalid = integer_from(\"forty-two\")\n\np value   # 42\np invalid # nil\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">18. Write and Read a Text File<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File.write replaces a file&#8217;s contents, while File.read returns the entire file as a string. For large files, process lines incrementally instead. chomp removes the record separator at the end of each line. File.foreach is memory-friendly because it does not load the whole file at once. Use a disposable file while experimenting, and inspect it between runs. File operations affect the filesystem outside the Ruby process, so cleanup and path choice deserve deliberate attention.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>path = \"notes.txt\"\n\nFile.write(path, \"Arrays\\nHashes\\nMethods\\n\")\n\nFile.foreach(path).with_index(1) do |line, number|\n  puts \"#{number}: #{line.chomp}\"\nend\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">19. Parse and Generate JSON<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Ruby&#8217;s standard JSON library converts JSON objects to hashes and JSON arrays to Ruby arrays. Require it before use. Never treat JSON from an external source as trusted simply because it parsed successfully. Validate the fields and types your program expects. Remove symbolize_names and inspect the keys returned by the parser. JSON object names are strings by default, which changes how the resulting hash must be accessed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>require \"json\"\n\njson = '{\"name\":\"Ruby\",\"dynamic\":true}'\ndata = JSON.parse(json, symbolize_names: true)\n\nputs data&#91;:name]\n\noutput = JSON.generate(language: data&#91;:name], topics: &#91;\"web\", \"scripts\"])\nputs output\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">20. Extract Data With a Regular Expression<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A regular expression is useful when the input has a predictable textual pattern. Named captures make the extracted pieces self-explanatory. For structured formats such as JSON or CSV, use a parser rather than a regular expression. Regex is best reserved for genuinely textual patterns. Try a line that does not match and confirm that the conditional body is skipped. Real input often contains partial or malformed records, so a non-match should be an expected case.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>log_line = \"2026-09-02 level=ERROR request_id=abc123\"\npattern = \/level=(?&lt;level&gt;\\w+) request_id=(?&lt;request_id&gt;\\w+)\/\n\nif match = log_line.match(pattern)\n  puts match&#91;:level]\n  puts match&#91;:request_id]\nend\n<\/code><\/pre>\n\n\n\n<h2 id=\"mini-project\" class=\"wp-block-heading\">Mini-Project: Count Word Frequency<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This final example combines strings, arrays, hashes, iteration, sorting, and formatted output. It counts words without caring about capitalisation or basic punctuation. Hash.new(0) gives an unseen word an initial count of zero. The sort key uses the negative count to put frequent words first, then sorts words alphabetically when their counts match.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>text = &lt;&lt;~TEXT\n  Ruby is expressive. Ruby is readable.\n  Readable code is easier to maintain.\nTEXT\n\nwords = text.downcase.scan(\/&#91;a-z]+\/)\ncounts = Hash.new(0)\n\nwords.each do |word|\n  counts&#91;word] += 1\nend\n\ncounts\n  .sort_by { |word, count| &#91;-count, word] }\n  .each { |word, count| puts format(\"%-10s %d\", word, count) }\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">How to Practise These Ruby Code Examples<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The best next step is to combine two or three snippets into something personally useful: a file renamer, expense total, log analyser, or command-line checklist. A small program you actually want tends to teach more than a large example copied without modification. Use the examples as starting points rather than finished answers. Predict one change, run it, and explain the result in your own words before moving on to a larger exercise.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Run each example unchanged so you know its starting behaviour.<\/li>\n\n\n\n<li>Predict what one small edit will do before running the program again.<\/li>\n\n\n\n<li>Turn fixed values into method arguments or terminal input.<\/li>\n\n\n\n<li>Add an edge case, such as an empty array, missing key, or invalid number.<\/li>\n\n\n\n<li>Read the exception rather than immediately deleting the line that caused it.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Official Ruby References<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For deeper detail, use the official documentation for <a href=\"https:\/\/docs.ruby-lang.org\/en\/master\/syntax\/literals_rdoc.html\">Ruby literals<\/a>, methods, Enumerable, File, and JSON. The documentation describes the full API; the Ruby code examples above show how the pieces fit into everyday programs.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn Ruby through 20 practical code examples covering strings, arrays, hashes, methods, classes, files, JSON, regex, and more.<\/p>\n","protected":false},"author":3,"featured_media":1183,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[],"class_list":["post-1184","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ruby-tips"],"blocksy_meta":{"styles_descriptor":{"styles":{"desktop":"","tablet":"","mobile":""},"google_fonts":[],"version":7}},"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Ruby Code Examples: 20 Practical Snippets<\/title>\n<meta name=\"description\" content=\"Explore 20 practical Ruby code examples covering variables, collections, methods, classes, files, JSON, regex, and a complete mini-project.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Ruby Code Examples: 20 Practical Snippets\" \/>\n<meta property=\"og:description\" content=\"Explore 20 practical Ruby code examples covering variables, collections, methods, classes, files, JSON, regex, and a complete mini-project.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/\" \/>\n<meta property=\"og:site_name\" content=\"Ruby-Doc Learn\" \/>\n<meta property=\"article:published_time\" content=\"2026-09-02T14:37:58+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-09-03T13:56:54+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/ruby-code-examples-featured.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"800\" \/>\n\t<meta property=\"og:image:height\" content=\"533\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"James Britt\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"James Britt\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/\"},\"author\":{\"name\":\"James Britt\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#\\\/schema\\\/person\\\/9e1feb9ed541d2a69da09fb4d10ea07b\"},\"headline\":\"Ruby Code Examples: 20 Practical Snippets for Beginners\",\"datePublished\":\"2026-09-02T14:37:58+00:00\",\"dateModified\":\"2026-09-03T13:56:54+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/\"},\"wordCount\":1800,\"publisher\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/ruby-code-examples-featured.webp\",\"articleSection\":[\"Ruby tips\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/\",\"url\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/\",\"name\":\"Ruby Code Examples: 20 Practical Snippets\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/ruby-code-examples-featured.webp\",\"datePublished\":\"2026-09-02T14:37:58+00:00\",\"dateModified\":\"2026-09-03T13:56:54+00:00\",\"description\":\"Explore 20 practical Ruby code examples covering variables, collections, methods, classes, files, JSON, regex, and a complete mini-project.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/#primaryimage\",\"url\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/ruby-code-examples-featured.webp\",\"contentUrl\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/ruby-code-examples-featured.webp\",\"width\":800,\"height\":533,\"caption\":\"Practical Ruby code examples for beginners and working developers.\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/ruby-code-examples\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Ruby Code Examples: 20 Practical Snippets for Beginners\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#website\",\"url\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/\",\"name\":\"Ruby-Doc Learn\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#organization\",\"name\":\"Ruby-Doc Learn\",\"url\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/ruby-doc-logo-transparent.png\",\"contentUrl\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/ruby-doc-logo-transparent.png\",\"width\":1650,\"height\":305,\"caption\":\"Ruby-Doc Learn\"},\"image\":{\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/#\\\/schema\\\/person\\\/9e1feb9ed541d2a69da09fb4d10ea07b\",\"name\":\"James Britt\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/jgb_self-portrait-20140914-150x150.png\",\"url\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/jgb_self-portrait-20140914-150x150.png\",\"contentUrl\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/jgb_self-portrait-20140914-150x150.png\",\"caption\":\"James Britt\"},\"description\":\"James Britt is a Ruby developer, writer, artist, musician and technologist. He created Ruby-Doc.org in 2002 and served as its long-term maintainer. He operates Neurogami and writes practical Ruby tutorials and code examples for Ruby-Doc Learn.\",\"sameAs\":[\"https:\\\/\\\/jamesbritt.com\\\/\"],\"url\":\"https:\\\/\\\/ruby-doc.org\\\/learn\\\/author\\\/jamesbritt\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Ruby Code Examples: 20 Practical Snippets","description":"Explore 20 practical Ruby code examples covering variables, collections, methods, classes, files, JSON, regex, and a complete mini-project.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/","og_locale":"en_US","og_type":"article","og_title":"Ruby Code Examples: 20 Practical Snippets","og_description":"Explore 20 practical Ruby code examples covering variables, collections, methods, classes, files, JSON, regex, and a complete mini-project.","og_url":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/","og_site_name":"Ruby-Doc Learn","article_published_time":"2026-09-02T14:37:58+00:00","article_modified_time":"2026-09-03T13:56:54+00:00","og_image":[{"width":800,"height":533,"url":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/ruby-code-examples-featured.webp","type":"image\/webp"}],"author":"James Britt","twitter_card":"summary_large_image","twitter_misc":{"Written by":"James Britt","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/#article","isPartOf":{"@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/"},"author":{"name":"James Britt","@id":"https:\/\/ruby-doc.org\/learn\/#\/schema\/person\/9e1feb9ed541d2a69da09fb4d10ea07b"},"headline":"Ruby Code Examples: 20 Practical Snippets for Beginners","datePublished":"2026-09-02T14:37:58+00:00","dateModified":"2026-09-03T13:56:54+00:00","mainEntityOfPage":{"@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/"},"wordCount":1800,"publisher":{"@id":"https:\/\/ruby-doc.org\/learn\/#organization"},"image":{"@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/ruby-code-examples-featured.webp","articleSection":["Ruby tips"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/","url":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/","name":"Ruby Code Examples: 20 Practical Snippets","isPartOf":{"@id":"https:\/\/ruby-doc.org\/learn\/#website"},"primaryImageOfPage":{"@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/#primaryimage"},"image":{"@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/ruby-code-examples-featured.webp","datePublished":"2026-09-02T14:37:58+00:00","dateModified":"2026-09-03T13:56:54+00:00","description":"Explore 20 practical Ruby code examples covering variables, collections, methods, classes, files, JSON, regex, and a complete mini-project.","breadcrumb":{"@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/#primaryimage","url":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/ruby-code-examples-featured.webp","contentUrl":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/ruby-code-examples-featured.webp","width":800,"height":533,"caption":"Practical Ruby code examples for beginners and working developers."},{"@type":"BreadcrumbList","@id":"https:\/\/ruby-doc.org\/learn\/ruby-code-examples\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/ruby-doc.org\/learn\/"},{"@type":"ListItem","position":2,"name":"Ruby Code Examples: 20 Practical Snippets for Beginners"}]},{"@type":"WebSite","@id":"https:\/\/ruby-doc.org\/learn\/#website","url":"https:\/\/ruby-doc.org\/learn\/","name":"Ruby-Doc Learn","description":"","publisher":{"@id":"https:\/\/ruby-doc.org\/learn\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/ruby-doc.org\/learn\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/ruby-doc.org\/learn\/#organization","name":"Ruby-Doc Learn","url":"https:\/\/ruby-doc.org\/learn\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ruby-doc.org\/learn\/#\/schema\/logo\/image\/","url":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/ruby-doc-logo-transparent.png","contentUrl":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/ruby-doc-logo-transparent.png","width":1650,"height":305,"caption":"Ruby-Doc Learn"},"image":{"@id":"https:\/\/ruby-doc.org\/learn\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/ruby-doc.org\/learn\/#\/schema\/person\/9e1feb9ed541d2a69da09fb4d10ea07b","name":"James Britt","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/jgb_self-portrait-20140914-150x150.png","url":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/jgb_self-portrait-20140914-150x150.png","contentUrl":"https:\/\/ruby-doc.org\/learn\/wp-content\/uploads\/2026\/09\/jgb_self-portrait-20140914-150x150.png","caption":"James Britt"},"description":"James Britt is a Ruby developer, writer, artist, musician and technologist. He created Ruby-Doc.org in 2002 and served as its long-term maintainer. He operates Neurogami and writes practical Ruby tutorials and code examples for Ruby-Doc Learn.","sameAs":["https:\/\/jamesbritt.com\/"],"url":"https:\/\/ruby-doc.org\/learn\/author\/jamesbritt\/"}]}},"_links":{"self":[{"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/posts\/1184","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/comments?post=1184"}],"version-history":[{"count":11,"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/posts\/1184\/revisions"}],"predecessor-version":[{"id":1279,"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/posts\/1184\/revisions\/1279"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/media\/1183"}],"wp:attachment":[{"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/media?parent=1184"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/categories?post=1184"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ruby-doc.org\/learn\/wp-json\/wp\/v2\/tags?post=1184"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}