Skip to content

Instantly share code, notes, and snippets.

@nickangtc
Last active March 9, 2022 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickangtc/adc5b8a18bb2b97ee5a5bf2c19b2cf41 to your computer and use it in GitHub Desktop.
Save nickangtc/adc5b8a18bb2b97ee5a5bf2c19b2cf41 to your computer and use it in GitHub Desktop.
How Rails extends Ruby builtin classes is actually really simple...
# scenario
# ========
# suppose we want functionality like so on any string:
# "racecar".palindrome? #=> true
#
# where should we could we add that functionality?
# in ruby, this is surprisingly possible:
class String
def palindrome?
self == self.reverse
end
end
"racecar".palindrome? #=> true
# notably, this is not completely overridding the
# builtin `String` class in ruby.
#
# instead, it opens up the builtin String class
# and adds a new instance method `palindrome?` to it,
# thereby enabling all string instances going forward
# to receive the message `palindrome?` and respond accordingly.
# nice.
@nickangtc
Copy link
Author

This is in many cases how Rails extends the functionality of Ruby. For example, the builtin String class doesn't have a blank? method, but in Rails, they do.

(This example was taken from the Rails Tutorial by Michael Hartl.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment