0

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!

  • 1
    Yikes! Why the rush to select an answer? What if some members are still working on answers? What if some members decide not to post an answer because the greenie has already been awarded? Many here wait at least a couple of hours before selecting an answer. The point is, there's no rush. When you have time, read the SO [faq](http://stackoverflow.com/help). – Cary Swoveland Mar 26 '16 at 00:40

1 Answers1

2

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • I prefer just `upcase`, rather than `self.upcase`. I know some like `self.` being explicit, but if written that way it should be mentioned that `self.` is not necessary. (What's `'!'` for?) – Cary Swoveland Mar 26 '16 at 00:33
  • 1
    `!` is just there to make it do something special that `upcase` alone wouldn't do. As for including `self`, that's to make it clear it's a method call. Some avoid doing this as a matter of principle, but I don't mind it. JavaScript requires `this` so it's not a bother for me. – tadman Mar 26 '16 at 00:43