Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify a Ruby class?

Tags:

ruby

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

like image 255
ben Avatar asked Jul 20 '26 16:07

ben


1 Answers

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.

like image 59
Reese Moore Avatar answered Jul 22 '26 09:07

Reese Moore