Module, mixins and file handling in ruby

Post on 12-Apr-2017

280 views 0 download

transcript

ModuleBy Ananta Raj lamichhane

ModuleModule are wrapper around the ruby code.Module cannot be instantiated.Module are used in conjunction with the classes.

Modules: namespacesbundle 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.

ExampleClass Date…....enddinner= Date.newdinner.date= Date.new

Conflict!!!

Module RomanticClass Date…....endenddinner= Romantic::Date.newdinner.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-insRuby 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.

Exampleclass Person attr_accessor :first_name, :last_name, :city, :state def full_name @first_name + " " + @last_name endend

class Teacherendclass Studentend

module ContactInfo attr_accessor :first_name, :last_name, :city, :state

def full_name @first_name + " " + @last_name endend

…...person.rb…….require 'contact_info'class Person include ContactInfoend….teacher.rb………...require 'contact_info'class Teacher include ContactInfoend...student.rb…………..require 'contact_info'class Student include ContactInfoend

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 >

ORclass student < Person attr_accesor :booksend

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 filesload:load the file everytime we call. hence return true on every calluse when you want to refresh the code and one to call the second time.disadvantageOnce 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 Mixinprovides a number of methods for objects which are iterable collection of other objects, like arrays, ranges or hashes. ex: sort, reject, detect, select, collect, injectThey 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.htmlhttp://www.ruby-doc.org/core-2.2.0/Hash.htmlhttp://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} endend

2.1.1 :006 > load 'to_do_list.rb' => true2.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

Exampleclass 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 workClass 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 basicInput: -> into a ruby program.Basic ruby inputsgetsOutput:-> from that program.Basic ruby outputsputsprint

IntroductionFile represents digital information that exists on durable storage.In Ruby File<IOFile is just a type of input and output.Read from the file-> inputWrite to the file->output

Writing(output) to filesfile= File.new(‘test.txt’, ‘w’) ‘W’: Write-only, truncates existing file to zero length or creates a new file for writingfile.puts “abcd”file.closeOR file.prints “efgh” or file.writes “ijkl”- returns number of character that it wrote.file << “mnop”

Reading(Input) from filesfile= File.new(‘test.txt’, ‘r’)"r" Read-only, starts at beginning of file (default mode)file.gets => "uvwx"Note: puts vs getsfile.gets -> get next line.file.read(4): takes in how many character to readfile.close.

Opening filesWe 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 ReadingReading 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 WritingWe can use write or puts to write files. Differenceputs- adds a line break to the end of stringswrite- 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 => 202.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 => 102.1.1 :025 > File.read('simple_file1.txt') => "where m i "

Deleting a fileirb :001 > File.new("dummy_file.txt", "w+") => #<File:dummy_file.txt>irb :002 > File.delete("dummy_file.txt") => 1

AssignmentsDay 4Class 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.