Search code examples
rubystringclassmethodsupcase

Re-open String class and add .upcase method in Ruby


Task: In Ruby I have to re-open the String class and add a new functionality my_new_method that calls the upcase method.

"abc".my_new_method

returns

"ABC"

I have tried with this code but the test said wrong number of arguments (0 for 1)

# Re-open String class
class String
  # Add the my_new_method method.
  def my_new_method(value)
    value.upcase
  end
end

Test:

Test.expect "abc".my_new_method == "ABC"

I know that I don't have to put an argument (value) but I don't know how to take the string written before.

Please try to help me. Thanks in advance!


Solution

  • Extending core classes is fine to do so long as you're careful, especially when it comes to re-writing core methods.

    Remember whenever you're inside an instance method then self always refers to the instance:

    def my_special_upcase
      self.upcase + '!'
    end
    

    So self refers to the string in question.