重新打开 String class 并在 Ruby 中添加 .upcase 方法
Re-open String class and add .upcase method in Ruby
任务: 在 Ruby 中,我必须重新打开字符串 class 并添加一个调用大写字母的新功能 my_new_method方法。
"abc".my_new_method
returns
"ABC"
我试过这段代码,但测试显示参数数量错误(0 代表 1)
# Re-open String class
class String
# Add the my_new_method method.
def my_new_method(value)
value.upcase
end
end
测试:
Test.expect "abc".my_new_method == "ABC"
我知道我不必输入参数(值),但我不知道如何取之前写的字符串。
请帮助我。提前致谢!
扩展核心 类 很好,只要您细心,尤其是在重写核心方法时。
请记住,无论何时在实例方法中,self
总是指实例:
def my_special_upcase
self.upcase + '!'
end
所以self
指的是有问题的字符串。
任务: 在 Ruby 中,我必须重新打开字符串 class 并添加一个调用大写字母的新功能 my_new_method方法。
"abc".my_new_method
returns
"ABC"
我试过这段代码,但测试显示参数数量错误(0 代表 1)
# Re-open String class
class String
# Add the my_new_method method.
def my_new_method(value)
value.upcase
end
end
测试:
Test.expect "abc".my_new_method == "ABC"
我知道我不必输入参数(值),但我不知道如何取之前写的字符串。
请帮助我。提前致谢!
扩展核心 类 很好,只要您细心,尤其是在重写核心方法时。
请记住,无论何时在实例方法中,self
总是指实例:
def my_special_upcase
self.upcase + '!'
end
所以self
指的是有问题的字符串。