Blocks

Build a big expertise of Ruby –
One small block of knowledge at a time.


Flexible Hash Arguments in Ruby

The double splat operator (**) allows methods to accept an arbitrary number of keyword arguments as a hash. Perfect for creating flexible APIs and handling optional parameters.

def greet(name:, age:, **options)
  puts "Hello #{name}, you are #{age} years old"
  puts "Additional info: #{options}" if options.any?
end

# Call with extra arguments
greet(name: "John", age: 30, city: "New York", occupation: "Developer")

Use it when you need to pass through additional options or create flexible method signatures. Great for API wrappers, configuration objects, and method delegation.

Dynamic Method Handling in Ruby

The method_missing hook allows you to handle calls to undefined methods. It's perfect for creating dynamic APIs and implementing flexible interfaces.

class User
  def method_missing(method_name, *args)
    if method_name.to_s.start_with?('find_by_')
      attribute = method_name.to_s.split('find_by_').last
      where(attribute => args.first)
    else
      super
    end
  end
end

# Now you can do:
User.find_by_name("John")

Great for creating dynamic finders, API wrappers, and configuration objects. Remember to implement respond_to_missing? and always call super for unhandled methods.

A Clean Way to Chain Object Modifications

The tap method yields an object to a block and returns the object itself. It's perfect for performing operations on an object while maintaining a clean chain.

# Without tap
user = User.new
user.name = "John"
user.save
return user

# With tap
User.new.tap do |user|
  user.name = "John"
  user.save
end

Great for object initialization, debugging method chains, and keeping your code DRY. Use it when you need to perform multiple operations on an object while maintaining method chaining.