stensootla
stensootla

Reputation: 14845

Ruby method overriding

I'm just starting out in Ruby and I've come across a very strange behavior of methods that I can't explain. For example:

class String
  def substitute
    gsub("a", "b")
  end
end

puts "aa".substitute # outputs: "bb"

How can this be? I don't pass any arguments to the 'substitute' method, how does it know which string to call the gsub method on? Is there some invisible attribute before the gsub method that can be left out?

Here's how a "usual" method should work, in my mind. It get's an argument and operates on that data. (However, in the previous example, there was no data that gsub could operate on?)

def substitute(arg)
  arg.gsub("a", "b")
end

Upvotes: 0

Views: 630

Answers (2)

ovhaag
ovhaag

Reputation: 1278

In your example

puts "aa".substitute # outputs: "bb"

The "aa" object is an instance of the class String. Objects know their contents or data and their class.

Because the "aa" object knows it is a String, you can call the method #substitute on it, which is defined in String.

Because the "aa" object knows it's contents or data, #substitute needs no argument to modify this data.

Upvotes: -1

nurettin
nurettin

Reputation: 11736

class String
  def substitute
    gsub("a", "b")
  end
end

is the same as

class String
  def substitute
    self.gsub("a", "b")
  end
end

That means gsub is called on the String instance which is "aa" in your case.

Upvotes: 6

Related Questions