DEV Community

loading...

Discussion on: NoMethodError: undefined method for nil:NilClass... Explained

Collapse
citizen428 profile image
Michael Kohl • Edited

if we wanted to very easily by monkeypatching the String class

An often overlooked possibility in Ruby is defining methods on instances of a class (instead of monkey-patching the class itself):

s = "a string"
def s.loveliness
  "👋 Ben"
end

s.loveliness
#=> "👋 Ben"
"another string".loveliness
# NoMethodError (undefined method `loveliness' for "another string":String)

I have used variations [1] of this pattern on occasion to add a method to an object to satisfy some duck-typed interface without the hassle of defining a wrapper class (generally when writing temp code for refactorings or other things that don't need to survice for a long time). It's no coincidence that this looks like a class method definition (def self.loneliness) btw, as it's the same principle, i.e. specifying the object that gets the method added to its singleton class.

Another alternative would be using Refinements, but I don't see them much in the wild and haven't used them often myself.

[1] Here's one such variation:

s.define_singleton_method(:loveliness) { "👋 Ben" }