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

What's hot

Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
Deepak Hagadur Bheemaraju
 
Lecture 9
Lecture 9Lecture 9
Lecture 24
Lecture 24Lecture 24
Lecture 24
Debasish Pratihari
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
PRN USM
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
Soba Arjun
 
Taking User Input in Java
Taking User Input in JavaTaking User Input in Java
Taking User Input in Java
Eftakhairul Islam
 
OOP, Networking, Linux/Unix
OOP, Networking, Linux/UnixOOP, Networking, Linux/Unix
OOP, Networking, Linux/Unix
Novita Sari
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
0php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-30php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-3Fafah Ranaivo
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
Surendar Meesala
 
1 intro
1 intro1 intro
1 intro
abha48
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Inheritance
Inheritance Inheritance
Inheritance
Parthipan Parthi
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
Ahmet Bulut
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
eman lotfy
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in Spring
ASG
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
(E Book) Asp .Net Tips, Tutorials And Code
(E Book) Asp .Net Tips,  Tutorials And Code(E Book) Asp .Net Tips,  Tutorials And Code
(E Book) Asp .Net Tips, Tutorials And Code
syedjee
 

What's hot (20)

Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Lecture 24
Lecture 24Lecture 24
Lecture 24
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
Taking User Input in Java
Taking User Input in JavaTaking User Input in Java
Taking User Input in Java
 
OOP, Networking, Linux/Unix
OOP, Networking, Linux/UnixOOP, Networking, Linux/Unix
OOP, Networking, Linux/Unix
 
Java collections
Java collectionsJava collections
Java collections
 
0php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-30php 5-online-cheat-sheet-v1-3
0php 5-online-cheat-sheet-v1-3
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
1 intro
1 intro1 intro
1 intro
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Inheritance
Inheritance Inheritance
Inheritance
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in Spring
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
(E Book) Asp .Net Tips, Tutorials And Code
(E Book) Asp .Net Tips,  Tutorials And Code(E Book) Asp .Net Tips,  Tutorials And Code
(E Book) Asp .Net Tips, Tutorials And Code
 

Similar to Module, mixins and file handling in ruby

FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Unit VI
Unit VI Unit VI
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
Vishal Dutt
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
Gagan Agrawal
 
H file handling
H file handlingH file handling
H file handling
missstevenson01
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
sadhana312471
 
Use Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.pptUse Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.ppt
manishchoudhary91861
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
Bhavsingh Maloth
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
20 ruby input output
20 ruby input output20 ruby input output
20 ruby input output
Walker Maidana
 
Python Programming - Files & Exceptions
Python Programming - Files & ExceptionsPython Programming - Files & Exceptions
Python Programming - Files & Exceptions
Omid AmirGhiasvand
 
Java notes
Java notesJava notes
Java notes
Upasana Talukdar
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
Inzamam Baig
 

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

FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
Unit VI
Unit VI Unit VI
Unit VI
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
 
H file handling
H file handlingH file handling
H file handling
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Use Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.pptUse Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.ppt
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
 
History
HistoryHistory
History
 
Python-files
Python-filesPython-files
Python-files
 
20 ruby input output
20 ruby input output20 ruby input output
20 ruby input output
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
My History
My HistoryMy History
My History
 
Python Programming - Files & Exceptions
Python Programming - Files & ExceptionsPython Programming - Files & Exceptions
Python Programming - Files & Exceptions
 
Java notes
Java notesJava notes
Java notes
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 

Recently uploaded

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 

Recently uploaded (20)

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 

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.