Last active
March 9, 2022 15:48
-
-
Save nickangtc/adc5b8a18bb2b97ee5a5bf2c19b2cf41 to your computer and use it in GitHub Desktop.
How Rails extends Ruby builtin classes is actually really simple...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.)