我想创建一个全局String方法,用作:"string".convert_to_date我可以像"abc".length或那样使用它"abc".upcase.
我该如何定义convert_to_date方法?
作为修补的替代方法,您还可以通过优化来定义修补程序.这将使补丁仅在某个范围内可用.这不一定是一个问题String.convert_to_date,但在大型项目中,通常建议避免彻底的monkeypatching,以避免与宝石的代码冲突.
精确定义和使用如下:
module StringRefinement
refine String do
def convert_to_date
self + " world"
end
end
end
class SomeClass
using StringRefinement
"hello".convert_to_date # => "hello world"
end
"hello".convert_to_date # => NoMethodError
Run Code Online (Sandbox Code Playgroud)
你可以在ruby中打开任何类来为它添加方法,你可以这样做
class String
def convert_to_date
# do something with the string, self will contain the value of the string
end
end
Run Code Online (Sandbox Code Playgroud)
这将使该方法可用于任何字符串对象,因此请确保您知道自己在做什么,并且没有副作用.
这称为猴子修补,我不确定这是否是没有更多上下文的最佳方式
如果您只是尝试将字符串日期转换为日期或时间对象,则已存在类似Time.parse或的方法DateTime.parse