Guide to Ruby Refinements

This coding exercise will teach you how to use Refinements in Ruby in order to add custom functionality to specific classes.

Sign Up to Start Your Own Code Camp

Ruby Refinements

View Video

Summary

Implement Refinements in Ruby so that a method can be added to a String class, but only for specific classes.

Exercise File

Code File

Exercise Description

Given the following class definition:

class ContentController
  def initialize(word)
    @word = word
  end

  def hidden_content
    @word.commentize
  end
end

Implement a Refinement to the String class that adds the commentize method, but only for specific classes (instead the global String class like typical monkey patching)

Sample Outpout

cc = ContentController.new("My String")
cc.hidden_content # "# My String"

Real World Usage

Monkey patching can cause a number of negative side effects in a program, by leveraging refinements you will be able to be specific about which classes can access the class changes.

Solution

Can be found on the solutions branch on github.

Jordan Hudgens

Jordan Hudgens

I've been a software engineer for the past decade and have traveled the world building applications and training individuals on a wide variety of topics.


View All Posts