# Ruby Refinements

DevFeed: [Ruby Refinements](<https://devfeed.tech/articles/ruby-refinements-21054.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2015/12/13/ruby-refinements/>)

Published: 2015-12-13T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [code](<https://devfeed.tech/tags/code.md>), [developer](<https://devfeed.tech/tags/developer.md>), [developers](<https://devfeed.tech/tags/developers.md>), [ruby](<https://devfeed.tech/tags/ruby.md>)

## AI overview

This article explains Ruby refinements as a scoped alternative to monkey patching. It shows how global changes to existing classes can create unexpected behavior and how refinements contain method changes within the context where they are needed.

## Source excerpt

The Ruby language provides many powerful tools for software engineers to utilize. For instance, classes that have been previously defined and evaluated can be reopened and changed. This is commonly referred to as "monkey patching", a term which elicits almost universal disdain among Ruby developers. The Problem A reason that monkey patched code has issues lies in the scope of the changed code. If previously defined code is changed at an arbitrary time, all other parts of the application suffer from those changes. Why would someone need to change an existing class? Perhaps an included gem needs to be altered in a small way to behave correctly in a very specific system. Or maybe, there exists a very dark area of a codebase that must not be touched directly for fear that the entire application will go under. Whatever the case, patching code that has been already defined happens, and it usually happens poorly. These problems can be especially nefarious if the patches are not in automatically loaded files. For example, say we have a Dog class: dog.rb class Dog attr_accessor :trained def bark "woof woof" end end Then in file loaded later, the bark method changes to be much more formal: training.rb class Training def train(dog) dog.trained = true dog.bark end end class Dog def bark "Woof woof, good sir." end end After the Traning class is loaded, any consumers of the Dog class will be in for a surprise whenever the bark method is called. Even worse, when a confused developer opens the dog.rb class to check bark's functionality, they will not see the patched version. dog = Dog.new dog.bark # => woof woof require './training' training = Training.new training.train(dog) # => Woof woof, good sir. dog = Dog.new dog.bark # => Woof woof, good sir. As shown, the second initialized Dog barks the same way as the trained Dog. Globally, the way a Dog barks has been changed after the training file has been included. Enter Refinements An alternative way to extend a class' functionality