Skip to content

Instantly share code, notes, and snippets.

@j2doll
Created January 18, 2018 08:15
Show Gist options
  • Select an option

  • Save j2doll/d0a55b355a7e26fd2406d0c2c7062e4c to your computer and use it in GitHub Desktop.

Select an option

Save j2doll/d0a55b355a7e26fd2406d0c2c7062e4c to your computer and use it in GitHub Desktop.
Sample of Ruby mixin
=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