开发者

How do I modify a Ruby class?

开发者 https://www.devze.com 2023-01-22 10:03 出处:网络
I need to add a getlocal method to DateTime in Ruby 1.9.2, as per the suggestion on this page. How 开发者_JAVA技巧do I do this? Thanks for readingYou can simply add data by opening a class definition

I need to add a getlocal method to DateTime in Ruby 1.9.2, as per the suggestion on this page. How 开发者_JAVA技巧do I do this? Thanks for reading


You can simply add data by opening a class definition like you would any other class definition.

class DateTime
  def getlocal
    self.to_time.getlocal.to_datetime
  end
end

Simply putting that in your file will monkey patch the method into the DateTime class.
When you open a class that already exists, you can add code to it or override existing methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消