Created
January 18, 2018 08:15
-
-
Save j2doll/d0a55b355a7e26fd2406d0c2c7062e4c to your computer and use it in GitHub Desktop.
Sample of Ruby mixin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| =begin | |
| to_file.rb | |
| sample of 'mixin' | |
| =end | |
| module ToFile | |
| def filename | |
| "object_#{self.object_id}.txt" | |
| end | |
| def to_f | |
| File.open(filename, 'w') { |file| file.write( to_s ) } # to_s() is implemented at class Person | |
| end | |
| end | |
| class Person | |
| include ToFile | |
| attr_accessor :name | |
| def initialize( name ) | |
| @name = name | |
| end | |
| def to_s | |
| name | |
| end | |
| end | |
| Person.new('matz').to_f # write a file that contained 'matz'. file name is 'object_***.txt'. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment