SlideShare a Scribd company logo
1 of 8
Download to read offline
3/25/2014
1
More Ruby programming
Iterators, duck typing, inheritance,
and mixins
Iterators
• 3.times { puts "hi" } # output “hi” 3 times
• [4,6,8].each { puts "hi" } # can "ignore" argument
• y = 7
[4,6,8].each { |x|
y = y + x
puts y
}
What is the value of y?
Iterators
• arr = [4,6,8,10]
arr2 = arr.map { |x| x + 1 }
puts arr2 # output another array,
# each element is the result of the block
• sum = arr.inject { |acc,elt| acc + elt }
puts sum # inject is like fold function
# acc is the initial value, elt is the array element
# result of the block is used as initial value
# to apply the block to the next array element
Iterators
• puts (arr.any? { |elt| elt < 0 })
# prints true if one element is negative
• def foo
eight = yield 4
twelve = yield 6
eight + twelve
end
• puts (foo { |x| x + x } ) # what is the output?
Closure
• cl = lambda {|z| z * y}
q = cl.call(9)
puts q
• def foo2 f
eight = f.call 4
twelve = bar f
eight + twelve
end
def bar f
f.call 6
end
puts (foo2 (lambda { |x| x + x })
Duck typing
• Use an instance that “behaves enough like”
the expected ones.
def double x
x + x
end
– double applies to any class of objects that has a +
method that takes self as argument
3/25/2014
2
Inheritance
• If a class C extends class D, then every
instance of C is also an instance of D
– C inherits the methods of D
– C can add new methods
– C can override inherited methods
– Unlike Java, Ruby fields are not part of a class
definition and therefore, not inherited
Point class
class Point
attr_reader :x, :y
attr_writer :x, :y
def initialize(x,y)
@x = x
@y = y
end
def distFromOrigin
Math.sqrt(x * x + y * y) # uses getter methods
end
end
ColorPoint extends Point
class ColorPoint < Point
attr_reader :color
attr_writer :color
# (say p.color = "green" rather than needing
# p.myColorSetter("green") which does @color="green" in its body)
def initialize(x,y,c="clear") # or could skip this and color starts unset
super(x,y)
@color = c
end
end
3D point extends point
class ThreeDPoint < Point
attr_reader :z
attr_writer :z
def initialize(x,y,z)
super(x,y)
@z = z
end
def distFromOrigin
d = super
Math.sqrt(d * d + z * z)
end
end
Polar point extends point
class PolarPoint < Point
def initialize (r, theta)
@r = r
@theta = theta
end
def x
@r * Math.cos(@theta)
end
def y
@r * Math.sin(@theta)
end
…
# distFromOrigin already works!!!
end
Polar point extends point
class PolarPoint < Point
…
def x= a
b = y # avoids multiple calls to y method
@theta = Math.atan (b / a)
@r = Math.sqrt(a*a + b*b)
self
end
def y= b
a = x # avoid multiple calls to x method
@theta = Math.atan (b / a)
@r = Math.sqrt (a*a + b*b)
self
end
# distFromOrigin already works!!!
end
3/25/2014
3
Dynamic dispatch
def distFromOrigin
Math.sqrt(x * x + y * y) # uses getter methods
end
Math.sqrt(self.x() * self.x() + self.y() * self.y())
This method inherited from Point class still works
because the method “x” and “y” are overridden
in the subclass PolarPoint
Multiple inheritance, interfaces, and
mixins
• Languages (C++) with multiple inheritance let one class
extend multiple other classes
– Most powerful option
– Has semantic problems
– Java and Ruby do not use it
• Interfaces: Java has single inheritance but a Java class can
implement multiple interfaces
– An interface defines method signatures but not implementation
• Mixins: Ruby allows a class to have only one super class but
can include any number of mixins
– Mixin is “just a pile of methods”
– Mixin provides behavior while interface only provides types,
which is not an issue for dynamic languages such as Ruby
Multiple Inheritance
• In some languages (such as C++) a class can
have more than one base class
• Seems simple at first: just inherit fields and
methods from all the base classes
• For example: a multifunction printer
MultiFunction
Printer Copier Scanner Fax
Collision Problem
• The different base classes are unrelated,
and may not have been designed to be
combined
• Scanner and Fax might both have a
method named transmit
• When MultiFunction.transmit is
called, what should happen?
MultiFunction
Printer Copier Scanner Fax
Diamond Problem
• A class may inherit from the same base
class through more than one path
• If A defines a field x, then B has one and so
does C
• Does D get two of them?
D
B C
A
Solvable, But…
• A language that supports multiple inheritance
must have mechanisms for handling these
problems
• Not all that tricky
• The question is, is the additional power worth
the additional language complexity?
• Java’s designers did not think so
3/25/2014
4
Living Without Multiple Inheritance
• One benefit of multiple inheritance is that a
class can have several unrelated types (like
Copier and Fax)
• This can be done in Java by using interfaces:
a class can implement any number of
interfaces
• Another benefit is inheriting
implementation from multiple base classes
• This is harder to accomplish with Java
public class MultiFunction {
private Printer myPrinter;
private Copier myCopier;
private Scanner myScanner;
private Fax myFax;
public void copy() {
myCopier.copy();
}
public void transmitScanned() {
myScanner.transmit();
}
public void sendFax() {
myFax.transmit();
}
…
}
Forwarding
Interfaces
• A method prototype just gives the method
name and type—no method body
• An interface in Java is a collection of
method prototypes
public interface Drawable {
void show(int xPos, int yPos);
void hide();
}
Implementing Interfaces
• A class can declare that it implements a
particular interface
• Then it must provide public method
definitions that match those in the interface
Examples
public class Icon implements Drawable {
public void show(int x, int y) {
… method body …
}
public void hide() {
… method body …
}
…more methods and fields…
}
public class Square implements Drawable, Scalable {
… all required methods of all interfaces implemented …
}
Why Use Interfaces?
• An interface can be implemented by many
classes:
• Interface name can be used as a reference
type:
public class Window implements Drawable …
public class MousePointer implements Drawable …
public class Oval implements Drawable …
Drawable d;
d = new Icon("i1.gif");
d.show(0,0);
d = new Oval(20,30);
d.show(0,0);
3/25/2014
5
Polymorphism With Interfaces
• Class of object referred to by d is not
known at compile time
• It is some class that implements
Drawable, so it has show and hide
methods that can be called
static void flashoff(Drawable d, int k) {
for (int i = 0; i < k; i++) {
d.show(0,0);
d.hide();
}
}
A More Complete Example
• A Worklist interface for a collection of
String objects
• Can be added to, removed from, and tested
for emptiness
public interface Worklist {
/**
* Add one String to the worklist.
* @param item the String to add
*/
void add(String item);
/**
* Test whether there are more elements in the
* worklist: that is, test whether more elements
* have been added than have been removed.
* @return true iff there are more elements
*/
boolean hasMore();
/**
* Remove one String from the worklist and return
* it. There must be at least one element in the
* worklist.
* @return the String item removed
*/
String remove();
}
Interface Documentation
• Comments are especially important in an
interface, since there is no code to help the
reader understand what each method is
supposed to do
• Worklist interface does not specify
ordering: could be a stack, a queue, or
something else
• We will do an implementation as a stack,
implemented using linked lists
/**
* A Node is an object that holds a String and a link
* to the next Node. It can be used to build linked
* lists of Strings.
*/
public class Node {
private String data; // Each node has a String...
private Node link; // and a link to the next Node
/**
* Node constructor.
* @param theData the String to store in this Node
* @param theLink a link to the next Node
*/
public Node(String theData, Node theLink) {
data = theData;
link = theLink;
}
3/25/2014
6
/**
* Accessor for the String data stored in this Node.
* @return our String item
*/
public String getData() {
return data;
}
/**
* Accessor for the link to the next Node.
* @return the next Node
*/
public Node getLink() {
return link;
}
}
/**
* A Stack is an object that holds a collection of
* Strings.
*/
public class Stack implements Worklist {
private Node top = null; // top Node in the stack
/**
* Push a String on top of this stack.
* @param data the String to add
*/
public void add(String data) {
top = new Node(data,top);
}
/**
* Test whether this stack has more elements.
* @return true if this stack is not empty
*/
public boolean hasMore() {
return (top!=null);
}
/**
* Pop the top String from this stack and return it.
* This should be called only if the stack is
* not empty.
* @return the popped String
*/
public String remove() {
Node n = top;
top = n.getLink();
return n.getData();
}
}
A Test
• Output: The cut worm forgives the plow.
• Other implementations of Worklist are
possible: Queue, PriorityQueue, etc.
Worklist w;
w = new Stack();
w.add("the plow.");
w.add("forgives ");
w.add("The cut worm ");
System.out.print(w.remove());
System.out.print(w.remove());
System.out.println(w.remove());
Mixins
• Ruby mixins are somewhere between multiple
inheritance and interfaces
– They provide actual code for classes to include them but
they are not classes themselves
– Do not have constructors or a separate notion of fields
module Color
attr_accessor :color
def darken
self.color = "dark " + self.color
end
end
Include a mixin in class definition
module Color
attr_accessor :color
def darken
self.color = "dark " + self.color
end
end
class ColorPoint < Point
include Color
end
3/25/2014
7
Method look up
• obj.m # obj is an instance of the class C
– Look in C for method m first
– Then look in the mixins included in C
• Later ones shadow earlier ones
– Look in C’s superclass
– Look in C’s superclass’ mixins
– Look in C’s super-superclass
– Continue until m is found or reach the Object class
Mixin may call hook methods
module Doubler
def double
self + self # uses self’s + method, not defined in Doubler
end
end
class AnotherPoint
attr_accessor :x, :y
include Doubler
def + other # add two points
ans = AnotherPoint.new
ans.x = self.x + other.x
ans.y = self.y + other.y
ans
end
end
class String
include Doubler
end
Convenient Ruby mixins
• Both Enumerable and Comparable are mixins in
Ruby
• Comparable provides =, !=, >, >=, <, and <=
– Assume the classes that include comparable has the
method <=>
• a <=> b < 0 if a < b
• a <=> b > 0 if a > b
• a <=> b = 0 if a == b
– A class like Integer only needs to define <=> method
and then include Comparable to have a bunch of
methods for comparison
An example use of Comparable
class Name
attr_accessor :first, :middle, :last
include Comparable
def initialize(first,last,middle="")
@first = first
@last = last
@middle = middle
end
def <=> other
l = @last <=> other.last # <=> defined on strings
return l if l != 0
f = @first <=> other.first
return f if f != 0
@middle <=> other.middle
end
end
Define Comparable methods
def > other
(self <=> other) > 0
end
Enumerable module
• Enumerable defines methods such as any?,
map, and inject
– Assume the enumerable classes have “each”
method
– Array class defines “each” method and includes
Enumerable mixin
3/25/2014
8
Enumerable example
class MyRange
include Enumerable
def initialize(low,high)
@low = low
@high = high
end
def each
i=@low
while i <= @high
yield i
i=i+1
end
end
end
Enumerable example
class MyRange
include Enumerable
def initialize(low,high)
@low = low
@high = high
end
def each
i=@low
while i <= @high
yield i
i=i+1
end
end
end
MyRange.new(4,8).inject{|x,y| x+y}
Enumerable example
class MyRange
include Enumerable
def initialize(low,high)
@low = low
@high = high
end
def each
i=@low
while i <= @high
yield i
i=i+1
end
end
end
MyRange.new(4,8).inject{|x,y| x+y}
def map
arr = []
each {|x| arr.push x }
arr
end

More Related Content

What's hot

String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 

What's hot (20)

Java generics
Java genericsJava generics
Java generics
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Comp102 lec 7
Comp102   lec 7Comp102   lec 7
Comp102 lec 7
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
C# programming
C# programming C# programming
C# programming
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
OOP
OOPOOP
OOP
 
Java introduction
Java introductionJava introduction
Java introduction
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
Scala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To KnowScala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To Know
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
OOP Core Concept
OOP Core ConceptOOP Core Concept
OOP Core Concept
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 
Java Generics
Java GenericsJava Generics
Java Generics
 

Viewers also liked

Game theory Bayesian Games at HelpWithAssignment.com
Game theory Bayesian Games at HelpWithAssignment.comGame theory Bayesian Games at HelpWithAssignment.com
Game theory Bayesian Games at HelpWithAssignment.com
HelpWithAssignment.com
 

Viewers also liked (14)

Scope
ScopeScope
Scope
 
Manufacturing Process Selection and Design
Manufacturing Process Selection and DesignManufacturing Process Selection and Design
Manufacturing Process Selection and Design
 
Network Programming Assignment Help
Network Programming Assignment HelpNetwork Programming Assignment Help
Network Programming Assignment Help
 
Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715
 
System Programming - Interprocess communication
System Programming - Interprocess communicationSystem Programming - Interprocess communication
System Programming - Interprocess communication
 
Get 24/7 Reliable Engineering Assignment Help, 100% error free, money back g...
Get 24/7 Reliable Engineering  Assignment Help, 100% error free, money back g...Get 24/7 Reliable Engineering  Assignment Help, 100% error free, money back g...
Get 24/7 Reliable Engineering Assignment Help, 100% error free, money back g...
 
Factorial Experiments
Factorial ExperimentsFactorial Experiments
Factorial Experiments
 
Game theory Bayesian Games at HelpWithAssignment.com
Game theory Bayesian Games at HelpWithAssignment.comGame theory Bayesian Games at HelpWithAssignment.com
Game theory Bayesian Games at HelpWithAssignment.com
 
Tips for writing a good biography
Tips for writing a good biographyTips for writing a good biography
Tips for writing a good biography
 
Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715
 
Scoping
ScopingScoping
Scoping
 
Cash Dividend Assignment Help
Cash Dividend Assignment Help Cash Dividend Assignment Help
Cash Dividend Assignment Help
 
System Programming Assignment Help- Signals
System Programming Assignment Help- SignalsSystem Programming Assignment Help- Signals
System Programming Assignment Help- Signals
 
Customer relationship management
Customer relationship managementCustomer relationship management
Customer relationship management
 

Similar to Ruby Programming Assignment Help

golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
Spam92
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
Mark Whitaker
 
Description of the project Purpose To implement a simple au.pdf
Description of the project Purpose To implement a simple au.pdfDescription of the project Purpose To implement a simple au.pdf
Description of the project Purpose To implement a simple au.pdf
adcrates2010
 

Similar to Ruby Programming Assignment Help (20)

Inheritance
InheritanceInheritance
Inheritance
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Bc0037
Bc0037Bc0037
Bc0037
 
Description of the project Purpose To implement a simple au.pdf
Description of the project Purpose To implement a simple au.pdfDescription of the project Purpose To implement a simple au.pdf
Description of the project Purpose To implement a simple au.pdf
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Abstraction
AbstractionAbstraction
Abstraction
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 

Recently uploaded

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

Ruby Programming Assignment Help

  • 1. 3/25/2014 1 More Ruby programming Iterators, duck typing, inheritance, and mixins Iterators • 3.times { puts "hi" } # output “hi” 3 times • [4,6,8].each { puts "hi" } # can "ignore" argument • y = 7 [4,6,8].each { |x| y = y + x puts y } What is the value of y? Iterators • arr = [4,6,8,10] arr2 = arr.map { |x| x + 1 } puts arr2 # output another array, # each element is the result of the block • sum = arr.inject { |acc,elt| acc + elt } puts sum # inject is like fold function # acc is the initial value, elt is the array element # result of the block is used as initial value # to apply the block to the next array element Iterators • puts (arr.any? { |elt| elt < 0 }) # prints true if one element is negative • def foo eight = yield 4 twelve = yield 6 eight + twelve end • puts (foo { |x| x + x } ) # what is the output? Closure • cl = lambda {|z| z * y} q = cl.call(9) puts q • def foo2 f eight = f.call 4 twelve = bar f eight + twelve end def bar f f.call 6 end puts (foo2 (lambda { |x| x + x }) Duck typing • Use an instance that “behaves enough like” the expected ones. def double x x + x end – double applies to any class of objects that has a + method that takes self as argument
  • 2. 3/25/2014 2 Inheritance • If a class C extends class D, then every instance of C is also an instance of D – C inherits the methods of D – C can add new methods – C can override inherited methods – Unlike Java, Ruby fields are not part of a class definition and therefore, not inherited Point class class Point attr_reader :x, :y attr_writer :x, :y def initialize(x,y) @x = x @y = y end def distFromOrigin Math.sqrt(x * x + y * y) # uses getter methods end end ColorPoint extends Point class ColorPoint < Point attr_reader :color attr_writer :color # (say p.color = "green" rather than needing # p.myColorSetter("green") which does @color="green" in its body) def initialize(x,y,c="clear") # or could skip this and color starts unset super(x,y) @color = c end end 3D point extends point class ThreeDPoint < Point attr_reader :z attr_writer :z def initialize(x,y,z) super(x,y) @z = z end def distFromOrigin d = super Math.sqrt(d * d + z * z) end end Polar point extends point class PolarPoint < Point def initialize (r, theta) @r = r @theta = theta end def x @r * Math.cos(@theta) end def y @r * Math.sin(@theta) end … # distFromOrigin already works!!! end Polar point extends point class PolarPoint < Point … def x= a b = y # avoids multiple calls to y method @theta = Math.atan (b / a) @r = Math.sqrt(a*a + b*b) self end def y= b a = x # avoid multiple calls to x method @theta = Math.atan (b / a) @r = Math.sqrt (a*a + b*b) self end # distFromOrigin already works!!! end
  • 3. 3/25/2014 3 Dynamic dispatch def distFromOrigin Math.sqrt(x * x + y * y) # uses getter methods end Math.sqrt(self.x() * self.x() + self.y() * self.y()) This method inherited from Point class still works because the method “x” and “y” are overridden in the subclass PolarPoint Multiple inheritance, interfaces, and mixins • Languages (C++) with multiple inheritance let one class extend multiple other classes – Most powerful option – Has semantic problems – Java and Ruby do not use it • Interfaces: Java has single inheritance but a Java class can implement multiple interfaces – An interface defines method signatures but not implementation • Mixins: Ruby allows a class to have only one super class but can include any number of mixins – Mixin is “just a pile of methods” – Mixin provides behavior while interface only provides types, which is not an issue for dynamic languages such as Ruby Multiple Inheritance • In some languages (such as C++) a class can have more than one base class • Seems simple at first: just inherit fields and methods from all the base classes • For example: a multifunction printer MultiFunction Printer Copier Scanner Fax Collision Problem • The different base classes are unrelated, and may not have been designed to be combined • Scanner and Fax might both have a method named transmit • When MultiFunction.transmit is called, what should happen? MultiFunction Printer Copier Scanner Fax Diamond Problem • A class may inherit from the same base class through more than one path • If A defines a field x, then B has one and so does C • Does D get two of them? D B C A Solvable, But… • A language that supports multiple inheritance must have mechanisms for handling these problems • Not all that tricky • The question is, is the additional power worth the additional language complexity? • Java’s designers did not think so
  • 4. 3/25/2014 4 Living Without Multiple Inheritance • One benefit of multiple inheritance is that a class can have several unrelated types (like Copier and Fax) • This can be done in Java by using interfaces: a class can implement any number of interfaces • Another benefit is inheriting implementation from multiple base classes • This is harder to accomplish with Java public class MultiFunction { private Printer myPrinter; private Copier myCopier; private Scanner myScanner; private Fax myFax; public void copy() { myCopier.copy(); } public void transmitScanned() { myScanner.transmit(); } public void sendFax() { myFax.transmit(); } … } Forwarding Interfaces • A method prototype just gives the method name and type—no method body • An interface in Java is a collection of method prototypes public interface Drawable { void show(int xPos, int yPos); void hide(); } Implementing Interfaces • A class can declare that it implements a particular interface • Then it must provide public method definitions that match those in the interface Examples public class Icon implements Drawable { public void show(int x, int y) { … method body … } public void hide() { … method body … } …more methods and fields… } public class Square implements Drawable, Scalable { … all required methods of all interfaces implemented … } Why Use Interfaces? • An interface can be implemented by many classes: • Interface name can be used as a reference type: public class Window implements Drawable … public class MousePointer implements Drawable … public class Oval implements Drawable … Drawable d; d = new Icon("i1.gif"); d.show(0,0); d = new Oval(20,30); d.show(0,0);
  • 5. 3/25/2014 5 Polymorphism With Interfaces • Class of object referred to by d is not known at compile time • It is some class that implements Drawable, so it has show and hide methods that can be called static void flashoff(Drawable d, int k) { for (int i = 0; i < k; i++) { d.show(0,0); d.hide(); } } A More Complete Example • A Worklist interface for a collection of String objects • Can be added to, removed from, and tested for emptiness public interface Worklist { /** * Add one String to the worklist. * @param item the String to add */ void add(String item); /** * Test whether there are more elements in the * worklist: that is, test whether more elements * have been added than have been removed. * @return true iff there are more elements */ boolean hasMore(); /** * Remove one String from the worklist and return * it. There must be at least one element in the * worklist. * @return the String item removed */ String remove(); } Interface Documentation • Comments are especially important in an interface, since there is no code to help the reader understand what each method is supposed to do • Worklist interface does not specify ordering: could be a stack, a queue, or something else • We will do an implementation as a stack, implemented using linked lists /** * A Node is an object that holds a String and a link * to the next Node. It can be used to build linked * lists of Strings. */ public class Node { private String data; // Each node has a String... private Node link; // and a link to the next Node /** * Node constructor. * @param theData the String to store in this Node * @param theLink a link to the next Node */ public Node(String theData, Node theLink) { data = theData; link = theLink; }
  • 6. 3/25/2014 6 /** * Accessor for the String data stored in this Node. * @return our String item */ public String getData() { return data; } /** * Accessor for the link to the next Node. * @return the next Node */ public Node getLink() { return link; } } /** * A Stack is an object that holds a collection of * Strings. */ public class Stack implements Worklist { private Node top = null; // top Node in the stack /** * Push a String on top of this stack. * @param data the String to add */ public void add(String data) { top = new Node(data,top); } /** * Test whether this stack has more elements. * @return true if this stack is not empty */ public boolean hasMore() { return (top!=null); } /** * Pop the top String from this stack and return it. * This should be called only if the stack is * not empty. * @return the popped String */ public String remove() { Node n = top; top = n.getLink(); return n.getData(); } } A Test • Output: The cut worm forgives the plow. • Other implementations of Worklist are possible: Queue, PriorityQueue, etc. Worklist w; w = new Stack(); w.add("the plow."); w.add("forgives "); w.add("The cut worm "); System.out.print(w.remove()); System.out.print(w.remove()); System.out.println(w.remove()); Mixins • Ruby mixins are somewhere between multiple inheritance and interfaces – They provide actual code for classes to include them but they are not classes themselves – Do not have constructors or a separate notion of fields module Color attr_accessor :color def darken self.color = "dark " + self.color end end Include a mixin in class definition module Color attr_accessor :color def darken self.color = "dark " + self.color end end class ColorPoint < Point include Color end
  • 7. 3/25/2014 7 Method look up • obj.m # obj is an instance of the class C – Look in C for method m first – Then look in the mixins included in C • Later ones shadow earlier ones – Look in C’s superclass – Look in C’s superclass’ mixins – Look in C’s super-superclass – Continue until m is found or reach the Object class Mixin may call hook methods module Doubler def double self + self # uses self’s + method, not defined in Doubler end end class AnotherPoint attr_accessor :x, :y include Doubler def + other # add two points ans = AnotherPoint.new ans.x = self.x + other.x ans.y = self.y + other.y ans end end class String include Doubler end Convenient Ruby mixins • Both Enumerable and Comparable are mixins in Ruby • Comparable provides =, !=, >, >=, <, and <= – Assume the classes that include comparable has the method <=> • a <=> b < 0 if a < b • a <=> b > 0 if a > b • a <=> b = 0 if a == b – A class like Integer only needs to define <=> method and then include Comparable to have a bunch of methods for comparison An example use of Comparable class Name attr_accessor :first, :middle, :last include Comparable def initialize(first,last,middle="") @first = first @last = last @middle = middle end def <=> other l = @last <=> other.last # <=> defined on strings return l if l != 0 f = @first <=> other.first return f if f != 0 @middle <=> other.middle end end Define Comparable methods def > other (self <=> other) > 0 end Enumerable module • Enumerable defines methods such as any?, map, and inject – Assume the enumerable classes have “each” method – Array class defines “each” method and includes Enumerable mixin
  • 8. 3/25/2014 8 Enumerable example class MyRange include Enumerable def initialize(low,high) @low = low @high = high end def each i=@low while i <= @high yield i i=i+1 end end end Enumerable example class MyRange include Enumerable def initialize(low,high) @low = low @high = high end def each i=@low while i <= @high yield i i=i+1 end end end MyRange.new(4,8).inject{|x,y| x+y} Enumerable example class MyRange include Enumerable def initialize(low,high) @low = low @high = high end def each i=@low while i <= @high yield i i=i+1 end end end MyRange.new(4,8).inject{|x,y| x+y} def map arr = [] each {|x| arr.push x } arr end