Skip to content

Chapter 6 of 7

Strings, Patterns, and Operators

Strings in Ruby can be constructed with single or double quotes, but only double-quoted strings support interpolation, where the result of any Ruby expression can be embedded with the #{} syntax. This allows you to write puts "Hello, #{name}!" instead of concatenating pieces together. For printing output, the puts method writes a string followed by a newline, print omits the newline, and p outputs the inspected representation of an object, which is invaluable for debugging complex data structures.

Regular expressions are first-class objects in Ruby, written between forward slashes. The match method applies a pattern to a string and returns a MatchData object, while the =~ operator returns the index of the first match or nil if no match is found. The gsub method replaces every occurrence of a pattern with a given replacement string or with the result of a block, making it easy to transform text programmatically, such as masking vowels or capitalizing words.

Ruby offers several convenience operators for everyday programming. The ternary operator provides a compact one-line conditional of the form condition ? true_value : false_value. The splat operator gathers extra positional arguments into an array or, when used at a call site, expands an array into individual arguments; the double splat does the same for keyword arguments. The safe navigation operator invokes a method only when the receiver is not nil, returning nil otherwise, which prevents the dreaded NoMethodError on undefined nil receivers. For multi-branch conditions, case/when offers readable pattern matching that uses the case-equality operator, so it works naturally with ranges, classes, and regular expressions as well as literal values.

All chapters
  1. 1Core Data Structures
  2. 2Blocks, Procs, and Lambdas
  3. 3Classes, Inheritance, and Modules
  4. 4Iterators and Functional Collections
  5. 5Exception Handling and File I/O
  6. 6Strings, Patterns, and Operators
  7. 7Metaprogramming and the Ruby Ecosystem

Drill it

Reading is not remembering. These come from the Ruby Programming deck:

Q

What is a Symbol in Ruby?

A Symbol is a lightweight, immutable identifier prefixed with a colon, e.g. :name. Symbols are stored in memory only once, making them more efficient than strin...

Q

How do you create an Array in Ruby?

An Array is an ordered collection created with square brackets or Array.new.Examples:nums = [1, 2, 3]words = %w[hello world]empty = Array.new(5, 0)

Q

How do you create a Hash in Ruby?

A Hash is a collection of key-value pairs.Examples:h = { name: "Alice", age: 30 }h = Hash.new(0)Access values with h[:name].

Q

What is a block in Ruby?

A block is an anonymous chunk of code enclosed in do...end or curly braces { } that can be passed to a method.Example:[1,2,3].each { |n| puts n }