SlideShare a Scribd company logo
Module
By Ananta Raj lamichhane
Module
Module are wrapper around the ruby code.
Module cannot be instantiated.
Module are used in conjunction with the
classes.
Modules: namespaces
bundle logically related object together.
identifies a set of names when objects having different
origins but the same names are mixed together.
-so that there is no ambiguity.
Example
Class Date
…....
end
dinner= Date.new
dinner.date= Date.new
Conflict!!!
Module Romantic
Class Date
…....
end
end
dinner= Romantic::Date.new
dinner.date= Date.new
:: is a constant lookup operator
Namespace can:
Keep class name distinct from another ruby class.
Ensure classes used in open source won't conflict.
Module:Mix-ins
Ruby doesn't let us have multiple inheritance.
For additional functionality-
place into a module and mixed it in to any class that needs
it.
Powerful way to keep the code organize.
Example
class Person
attr_accessor :first_name, :last_name, :city,
:state
def full_name
@first_name + " " + @last_name
end
end
class Teacher
end
class Student
end
module ContactInfo
attr_accessor :first_name, :last_name, :city, :state
def full_name
@first_name + " " + @last_name
end
end
…...person.rb…….
require 'contact_info'
class Person
include ContactInfo
end
….teacher.rb………...
require 'contact_info'
class Teacher
include ContactInfo
end
...student.rb…………..
require 'contact_info'
class Student
include ContactInfo
end
2.1.1 :002 > t= Teacher.new
=> #<Teacher:0x00000004576198>
2.1.1 :003 > t.first_name="tfn"
=> "tfn"
2.1.1 :004 > t.last_name="tln"
=> "tln"
2.1.1 :005 > t.full_name
=> "tfn tln"
2.1.1 :006 > p= Person.new
=> #<Person:0x0000000454b5b0>
2.1.1 :007 > p.first_name="pfn"
=> "pfn"
2.1.1 :008 > p.last_name="pln"
=> "pln"
2.1.1 :009 > p.full_name
=> "pfn pln"
2.1.1 :010 >
OR
class student < Person
attr_accesor :books
end
Load , Require and
Include
Modules are usually kept in separate file.
Need to have a way to load modules into ruby.
include:
use module as maxin.
has nothing to do with loading the files
load:
load the file everytime we call. hence return true on every call
use when you want to refresh the code and one to call the second time.
disadvantage
Once ruby sees the file, there is no reason to call it again.
The code in load execute every time we call it .
require:
Keep track of the fact that is included.
only include if it has not been loaded before.
load source file only once.
Enumerable as a Mixin
Modules:Enumerable as Mixin
provides a number of methods for objects which are
iterable collection of other objects, like arrays, ranges or
hashes.
ex: sort, reject, detect, select, collect, inject
They may have slightly different behaviour in each one but are the same functionality.
must provide method each,-yields every member of the
collection one-by-one.
each-takes the block of code and iterates all the object of
the collection, passing it to the given block.
http://www.ruby-doc.org/core-2.2.0/Array.html
http://www.ruby-doc.org/core-2.2.0/Hash.html
http://www.ruby-doc.org/core-2.2.0/Range.html
class ToDoList
include Enumerable
attr_accessor :items
def initialize
@items = []
end
def each
@items.each {|item| yield item}
end
end
2.1.1 :006 > load 'to_do_list.rb'
=> true
2.1.1 :007 > tdl= ToDoList.new
=> #<ToDoList:0x000000028d12b8 @items=[]>
2.1.1 :009 > tdl.items= ["aaaa","bbbbbbbb","ddddddd"]
=> ["aaaa", "bbbbbbbb", "ddddddd"]
2.1.1 :011 > tdl.select {|i| i.length >4}
=> ["bbbbbbbb", "ddddddd"]
Comparable as Mixin
compare the objects- if they are equal, less or greater than other, and to sort
the collection of such objects.
The class must define the <=> (Spaceship) operator, which compares the
receiver against another object,
Ruby built-in object, like Fixnum or String, use this mixin to provide comparing
operator.
returns -1 if the left object is greater than the right one, 0 when they are equal
and 1 in case the right is greater then the left
Example
class Server
attr_reader :name, :no_processors, :memory_gb # we must provide readers to
this attributes
include Comparable # because we are comparing the other
Server with self
def initialize(name, no_processors, memory_gb)
@name = name
@no_processors = no_processors
@memory_gb = memory_gb
end
# def inspect
# "/Server: #{@name}: #{@no_processors} procs, #{@memory_gb} GiB mem/"
# end
def <=>(other)
if self.no_processors == other.no_processors # if there is the
same number of procs
self.memory_gb <=> other.memory_gb #
comparing memory
else
self.no_processors <=> other.no_processors # otherwise
comparing the number of processors
end
endend
Class work
Class Assignment : Write a class Animal with attributes name and
scientific_name. Write a class Human with attributes first_name, last_name and
scientific_name. Write a mixin called Name which has a method
complete_name. Include this mixin in both Animal and Human class.
The method should return “name(scientific_name)” for animals e.g. Frog(Rana
Tigrina). For Human it should return “first_name last_name(scientific name)”
e.g. John Doe(Homo Sapiens)
File handling
Input/Output basic
Input: -> into a ruby program.
Basic ruby inputs
gets
Output:-> from that program.
Basic ruby outputs
puts
print
Introduction
File represents digital information that exists on durable storage.
In Ruby File<IO
File is just a type of input and output.
Read from the file-> input
Write to the file->output
Writing(output) to files
file= File.new(‘test.txt’, ‘w’)
‘W’: Write-only, truncates existing file
to zero length or creates a new file for writing
file.puts “abcd”
file.close
OR
file.prints “efgh” or
file.writes “ijkl”- returns number of character that it wrote.
file << “mnop”
Reading(Input) from files
file= File.new(‘test.txt’, ‘r’)
"r" Read-only, starts at beginning of file (default mode)
file.gets
=> "uvwx"
Note: puts vs gets
file.gets -> get next line.
file.read(4): takes in how many character to read
file.close.
Opening files
We open an existing file using
File.open(“test.txt”, ‘r’).
We will pass the file name and a second
argument which will decide how the file will be
opened.
Open File For Reading
Reading file contents is easy in Ruby. Here are two options:
File.read("file_name") - Spits out entire contents of the file.
File.readlines("file_name") - Reads the entire file based on
individual lines and returns those lines in an array.
"r" Read-only, starts at beginning of file
(default mode).
"r+" Read-write, starts at beginning of file.
"w" Write-only, truncates existing file
to zero length or creates a new file
for writing.
"w+" Read-write, truncates existing file to zero
length
or creates a new file for reading and
writing.
"a" Write-only, starts at end of file if file exists,
otherwise creates a new file for
writing.
"a+" Read-write, starts at end of file if file exists,
otherwise creates a new file for
reading and
writing.
Open File For Writing
We can use write or puts to write files.
Difference
puts- adds a line break to the end of strings
write- does not.
File.open("simple_file.txt", "w") { |file|
file.write("adding first line of text") }
Note: the file closes at the end of the block.
Other examples:
2.1.1 :017 > File.read('simple_file1.txt')
=> "adding first line of text"
2.1.1 :018 > File.open('simple_file1.txt','a+') do |file|
2.1.1 :019 > file.write('writing to the file1')
2.1.1 :020?> end
=> 20
2.1.1 :021 > File.read('simple_file1.txt')
=> "adding first line of textwriting to the file1"
2.1.1 :022 > File.open('simple_file1.txt','w+') do |file|
2.1.1 :023 > file.write('where m i ')
2.1.1 :024?> end
=> 10
2.1.1 :025 > File.read('simple_file1.txt')
=> "where m i "
Deleting a file
irb :001 > File.new("dummy_file.txt", "w+")
=> #<File:dummy_file.txt>
irb :002 > File.delete("dummy_file.txt")
=> 1
Assignments
Day 4
Class Assignment 1: Write a module named MyFileModule. It should following methods:
a. create_file(path)
b. edit_file(path,content)
c. delete_file(path)
Necessary exception handling should be done.
Class Assignment 2: Write a class Animal with attributes name and scientific_name. Write a class Human with attributes
first_name, last_name and scientific_name. Write a mixin called Name which has a method complete_name. Include this mixin in
both Animal and Human class.
The method should return “name(scientific_name)” for animals e.g. Frog(Rana Tigrina). For Human it should return “first_name
last_name(scientific name)” e.g. John Doe(Homo Sapiens)
1. Write a program to adjust time in a movie subtitle. The input to the program should be path to the subtitle file and adjust time in
seconds (positive value to increase and negative value to decrease time). The program then creates a new subtitle file with
adjusted time without changing.

More Related Content

PPTX
Chapter 08 data file handling
PPTX
Functions in python
PPT
Chapter 12 - File Input and Output
PPT
Java Input Output and File Handling
PPSX
Dr. Rajeshree Khande - Java Interactive input
PDF
Files and streams
PDF
08. handling file streams
PPTX
Chapter 16 Dictionaries
Chapter 08 data file handling
Functions in python
Chapter 12 - File Input and Output
Java Input Output and File Handling
Dr. Rajeshree Khande - Java Interactive input
Files and streams
08. handling file streams
Chapter 16 Dictionaries

What's hot (20)

PPT
Chapter 4 - Defining Your Own Classes - Part I
PPTX
9 Inputs & Outputs
PDF
PDF
Lecture 24
PPT
File Input & Output
PDF
Python Dictionary
PPT
Taking User Input in Java
PDF
OOP, Networking, Linux/Unix
PDF
Java collections
PDF
0php 5-online-cheat-sheet-v1-3
DOCX
Java collections notes
PPTX
1 intro
PDF
Java I/o streams
PPTX
Inheritance
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
KEY
Programming with Python - Week 3
PPTX
Python dictionary
PPTX
Dependency Injection in Spring
 
PPT
Java collections concept
PDF
(E Book) Asp .Net Tips, Tutorials And Code
Chapter 4 - Defining Your Own Classes - Part I
9 Inputs & Outputs
Lecture 24
File Input & Output
Python Dictionary
Taking User Input in Java
OOP, Networking, Linux/Unix
Java collections
0php 5-online-cheat-sheet-v1-3
Java collections notes
1 intro
Java I/o streams
Inheritance
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Programming with Python - Week 3
Python dictionary
Dependency Injection in Spring
 
Java collections concept
(E Book) Asp .Net Tips, Tutorials And Code
Ad

Similar to Module, mixins and file handling in ruby (20)

PDF
Master of computer application python programming unit 3.pdf
PPTX
FIle Handling and dictionaries.pptx
PDF
PPTX
Python files / directories part16
PDF
Python programming : Files
PPTX
UNIT –5.pptxpython for engineering students
PPTX
01 file handling for class use class pptx
ODP
Java 7 Features and Enhancements
PPTX
H file handling
PPTX
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
PPTX
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
DOCX
These questions will be a bit advanced level 2
PDF
oblect oriented programming language in java notes .pdf
PPTX
FILE HANDLING IN PYTHON Presentation Computer Science
PPT
Use Classes with Object-Oriented Programming in C++.ppt
PPTX
C++ - UNIT_-_V.pptx which contains details about File Concepts
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
PPTX
FILE HANDLING.pptx
PPTX
file handling in python using exception statement
PPTX
File handling for reference class 12.pptx
Master of computer application python programming unit 3.pdf
FIle Handling and dictionaries.pptx
Python files / directories part16
Python programming : Files
UNIT –5.pptxpython for engineering students
01 file handling for class use class pptx
Java 7 Features and Enhancements
H file handling
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
These questions will be a bit advanced level 2
oblect oriented programming language in java notes .pdf
FILE HANDLING IN PYTHON Presentation Computer Science
Use Classes with Object-Oriented Programming in C++.ppt
C++ - UNIT_-_V.pptx which contains details about File Concepts
chapter 2(IO and stream)/chapter 2, IO and stream
FILE HANDLING.pptx
file handling in python using exception statement
File handling for reference class 12.pptx
Ad

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
DOCX
The AUB Centre for AI in Media Proposal.docx
PPT
Teaching material agriculture food technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Machine learning based COVID-19 study performance prediction
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
cuic standard and advanced reporting.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
A Presentation on Artificial Intelligence
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Network Security Unit 5.pdf for BCA BBA.
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The AUB Centre for AI in Media Proposal.docx
Teaching material agriculture food technology
Big Data Technologies - Introduction.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Machine learning based COVID-19 study performance prediction
A comparative analysis of optical character recognition models for extracting...
The Rise and Fall of 3GPP – Time for a Sabbatical?
cuic standard and advanced reporting.pdf
sap open course for s4hana steps from ECC to s4
Unlocking AI with Model Context Protocol (MCP)
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
MIND Revenue Release Quarter 2 2025 Press Release
A Presentation on Artificial Intelligence
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Programs and apps: productivity, graphics, security and other tools
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Empathic Computing: Creating Shared Understanding
Network Security Unit 5.pdf for BCA BBA.

Module, mixins and file handling in ruby

  • 1. Module By Ananta Raj lamichhane
  • 2. Module Module are wrapper around the ruby code. Module cannot be instantiated. Module are used in conjunction with the classes.
  • 3. Modules: namespaces bundle logically related object together. identifies a set of names when objects having different origins but the same names are mixed together. -so that there is no ambiguity.
  • 4. Example Class Date ….... end dinner= Date.new dinner.date= Date.new Conflict!!! Module Romantic Class Date ….... end end dinner= Romantic::Date.new dinner.date= Date.new :: is a constant lookup operator
  • 5. Namespace can: Keep class name distinct from another ruby class. Ensure classes used in open source won't conflict.
  • 6. Module:Mix-ins Ruby doesn't let us have multiple inheritance. For additional functionality- place into a module and mixed it in to any class that needs it. Powerful way to keep the code organize.
  • 7. Example class Person attr_accessor :first_name, :last_name, :city, :state def full_name @first_name + " " + @last_name end end class Teacher end class Student end
  • 8. module ContactInfo attr_accessor :first_name, :last_name, :city, :state def full_name @first_name + " " + @last_name end end
  • 9. …...person.rb……. require 'contact_info' class Person include ContactInfo end ….teacher.rb………... require 'contact_info' class Teacher include ContactInfo end ...student.rb………….. require 'contact_info' class Student include ContactInfo end 2.1.1 :002 > t= Teacher.new => #<Teacher:0x00000004576198> 2.1.1 :003 > t.first_name="tfn" => "tfn" 2.1.1 :004 > t.last_name="tln" => "tln" 2.1.1 :005 > t.full_name => "tfn tln" 2.1.1 :006 > p= Person.new => #<Person:0x0000000454b5b0> 2.1.1 :007 > p.first_name="pfn" => "pfn" 2.1.1 :008 > p.last_name="pln" => "pln" 2.1.1 :009 > p.full_name => "pfn pln" 2.1.1 :010 >
  • 10. OR class student < Person attr_accesor :books end
  • 11. Load , Require and Include
  • 12. Modules are usually kept in separate file. Need to have a way to load modules into ruby.
  • 13. include: use module as maxin. has nothing to do with loading the files load: load the file everytime we call. hence return true on every call use when you want to refresh the code and one to call the second time. disadvantage Once ruby sees the file, there is no reason to call it again. The code in load execute every time we call it . require: Keep track of the fact that is included. only include if it has not been loaded before. load source file only once.
  • 15. Modules:Enumerable as Mixin provides a number of methods for objects which are iterable collection of other objects, like arrays, ranges or hashes. ex: sort, reject, detect, select, collect, inject They may have slightly different behaviour in each one but are the same functionality. must provide method each,-yields every member of the collection one-by-one. each-takes the block of code and iterates all the object of the collection, passing it to the given block.
  • 17. class ToDoList include Enumerable attr_accessor :items def initialize @items = [] end def each @items.each {|item| yield item} end end 2.1.1 :006 > load 'to_do_list.rb' => true 2.1.1 :007 > tdl= ToDoList.new => #<ToDoList:0x000000028d12b8 @items=[]> 2.1.1 :009 > tdl.items= ["aaaa","bbbbbbbb","ddddddd"] => ["aaaa", "bbbbbbbb", "ddddddd"] 2.1.1 :011 > tdl.select {|i| i.length >4} => ["bbbbbbbb", "ddddddd"]
  • 19. compare the objects- if they are equal, less or greater than other, and to sort the collection of such objects. The class must define the <=> (Spaceship) operator, which compares the receiver against another object, Ruby built-in object, like Fixnum or String, use this mixin to provide comparing operator. returns -1 if the left object is greater than the right one, 0 when they are equal and 1 in case the right is greater then the left
  • 20. Example class Server attr_reader :name, :no_processors, :memory_gb # we must provide readers to this attributes include Comparable # because we are comparing the other Server with self def initialize(name, no_processors, memory_gb) @name = name @no_processors = no_processors @memory_gb = memory_gb end # def inspect # "/Server: #{@name}: #{@no_processors} procs, #{@memory_gb} GiB mem/" # end def <=>(other) if self.no_processors == other.no_processors # if there is the same number of procs self.memory_gb <=> other.memory_gb # comparing memory else self.no_processors <=> other.no_processors # otherwise comparing the number of processors end endend
  • 21. Class work Class Assignment : Write a class Animal with attributes name and scientific_name. Write a class Human with attributes first_name, last_name and scientific_name. Write a mixin called Name which has a method complete_name. Include this mixin in both Animal and Human class. The method should return “name(scientific_name)” for animals e.g. Frog(Rana Tigrina). For Human it should return “first_name last_name(scientific name)” e.g. John Doe(Homo Sapiens)
  • 23. Input/Output basic Input: -> into a ruby program. Basic ruby inputs gets Output:-> from that program. Basic ruby outputs puts print
  • 24. Introduction File represents digital information that exists on durable storage. In Ruby File<IO File is just a type of input and output. Read from the file-> input Write to the file->output
  • 25. Writing(output) to files file= File.new(‘test.txt’, ‘w’) ‘W’: Write-only, truncates existing file to zero length or creates a new file for writing file.puts “abcd” file.close OR file.prints “efgh” or file.writes “ijkl”- returns number of character that it wrote. file << “mnop”
  • 26. Reading(Input) from files file= File.new(‘test.txt’, ‘r’) "r" Read-only, starts at beginning of file (default mode) file.gets => "uvwx" Note: puts vs gets file.gets -> get next line. file.read(4): takes in how many character to read file.close.
  • 27. Opening files We open an existing file using File.open(“test.txt”, ‘r’). We will pass the file name and a second argument which will decide how the file will be opened. Open File For Reading Reading file contents is easy in Ruby. Here are two options: File.read("file_name") - Spits out entire contents of the file. File.readlines("file_name") - Reads the entire file based on individual lines and returns those lines in an array.
  • 28. "r" Read-only, starts at beginning of file (default mode). "r+" Read-write, starts at beginning of file. "w" Write-only, truncates existing file to zero length or creates a new file for writing. "w+" Read-write, truncates existing file to zero length or creates a new file for reading and writing. "a" Write-only, starts at end of file if file exists, otherwise creates a new file for writing. "a+" Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing.
  • 29. Open File For Writing We can use write or puts to write files. Difference puts- adds a line break to the end of strings write- does not. File.open("simple_file.txt", "w") { |file| file.write("adding first line of text") } Note: the file closes at the end of the block.
  • 30. Other examples: 2.1.1 :017 > File.read('simple_file1.txt') => "adding first line of text" 2.1.1 :018 > File.open('simple_file1.txt','a+') do |file| 2.1.1 :019 > file.write('writing to the file1') 2.1.1 :020?> end => 20 2.1.1 :021 > File.read('simple_file1.txt') => "adding first line of textwriting to the file1" 2.1.1 :022 > File.open('simple_file1.txt','w+') do |file| 2.1.1 :023 > file.write('where m i ') 2.1.1 :024?> end => 10 2.1.1 :025 > File.read('simple_file1.txt') => "where m i "
  • 31. Deleting a file irb :001 > File.new("dummy_file.txt", "w+") => #<File:dummy_file.txt> irb :002 > File.delete("dummy_file.txt") => 1
  • 32. Assignments Day 4 Class Assignment 1: Write a module named MyFileModule. It should following methods: a. create_file(path) b. edit_file(path,content) c. delete_file(path) Necessary exception handling should be done. Class Assignment 2: Write a class Animal with attributes name and scientific_name. Write a class Human with attributes first_name, last_name and scientific_name. Write a mixin called Name which has a method complete_name. Include this mixin in both Animal and Human class. The method should return “name(scientific_name)” for animals e.g. Frog(Rana Tigrina). For Human it should return “first_name last_name(scientific name)” e.g. John Doe(Homo Sapiens) 1. Write a program to adjust time in a movie subtitle. The input to the program should be path to the subtitle file and adjust time in seconds (positive value to increase and negative value to decrease time). The program then creates a new subtitle file with adjusted time without changing.