Reputation: 11914
In Metaprogramming Ruby I saw this code
class String
def to_alphanumeric
gsub /[^\w\s]/, ''
end
end
Here it adds a method to_alphanumeric, which substitutes punctuations with whitespace, to the standard class String. What confuses me is, since we do not specify which object gsub works on, how does Ruby know here we actually mean gsub works on the String obj itself instead of something else? Or put it in another way, does Ruby automatically rewrite it as self.gsub?
Upvotes: 0
Views: 70
Reputation: 258478
The implicit receiver in Ruby is always self
(and self
is different in different contexts, of course).
Ruby doesn't "automatically rewrite it as self.gsub
" per se, because calling a private method with an explicit self
receiver will raise an exception (and gsub
is a public method here anyway).
Upvotes: 7