Ruby Examples

Ruby syntax with classes, symbols, and metaprogramming

Ruby Class Example

Object-oriented programming with Ruby:

# Simple class class Greeter def initialize(name) @name = name end def greet puts "Hello, #{@name}!" end end # Usage user = Greeter.new('World') user.greet # Symbols and regex status = :ok pattern = /foo.+bar/i # Percent literals words = %w{alpha beta gamma} # Command output = `uname -a`

Predicate and Bang Methods

Methods ending in ? express queries, while methods ending in ! commonly signal mutation or failure:

class Document def initialize @published_at = nil end def published? !@published_at.nil? end def publish! raise 'Already published' if published? @published_at = Time.now end end document = Document.new document.published? document.publish! # Predicate and bang calls can also omit a receiver. publish! if ready? save! document if valid? # Question marks and bangs are also valid in symbols. callbacks = [:ready?, :save!]

Blocks and Enumerable

Collections, blocks, ranges, and chained method calls:

numbers = (1..10).to_a even_squares = numbers .select { |number| number.even? } .map { |number| number * number } total = even_squares.reduce(0) do |sum, number| sum + number end puts "Even squares: #{even_squares.join(', ')}" puts "Total: #{total}"

Metaprogramming

Dynamically defining predicate and bang methods:

class FeatureFlags def initialize @enabled = {} end [:search, :billing, :reports].each do |feature| define_method("#{feature}?") do @enabled.fetch(feature, false) end define_method("enable_#{feature}!") do @enabled[feature] = true end end end flags = FeatureFlags.new flags.enable_search! puts flags.search?