SlideShare une entreprise Scribd logo
1  sur  8
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
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!Kel Cecil
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
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 Ganesh Samarthyam
 
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 KnowLightbend
 
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 PitfallsRakesh Waghela
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slidesOCaml
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 

Tendances (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
 

En vedette

Elk Canada
Elk CanadaElk Canada
Elk Canadafruitmax
 
Get Multiple Regression Assignment Help
Get Multiple Regression Assignment Help Get Multiple Regression Assignment Help
Get Multiple Regression Assignment Help HelpWithAssignment.com
 
Personal Memoir Slideshow
Personal Memoir SlideshowPersonal Memoir Slideshow
Personal Memoir SlideshowJosh Maroney
 
Astra Gin, A Nu Liv Science Nutraceutical Ingredient For Increasing Nutrient ...
Astra Gin, A Nu Liv Science Nutraceutical Ingredient For Increasing Nutrient ...Astra Gin, A Nu Liv Science Nutraceutical Ingredient For Increasing Nutrient ...
Astra Gin, A Nu Liv Science Nutraceutical Ingredient For Increasing Nutrient ...fruitmax
 
Horario 2012 1_electronica_yopal (1)
Horario 2012 1_electronica_yopal (1)Horario 2012 1_electronica_yopal (1)
Horario 2012 1_electronica_yopal (1)andrea botia
 
"営業マン"な自社サイトを作る
"営業マン"な自社サイトを作る"営業マン"な自社サイトを作る
"営業マン"な自社サイトを作るDigical Media
 
Nuliv An Overview Of Nu Liv Science 2010 6 21
Nuliv An Overview Of Nu Liv Science 2010 6 21Nuliv An Overview Of Nu Liv Science 2010 6 21
Nuliv An Overview Of Nu Liv Science 2010 6 21fruitmax
 
Horario 2012_ Ingeniería Electrónica
Horario 2012_ Ingeniería  Electrónica Horario 2012_ Ingeniería  Electrónica
Horario 2012_ Ingeniería Electrónica andrea botia
 
Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715HelpWithAssignment.com
 
New England Business Expo 2009
New England Business Expo 2009New England Business Expo 2009
New England Business Expo 2009Dennys_Catering
 
株式会社デジカルメディア事業部 サービス紹介 Ver1.0
株式会社デジカルメディア事業部 サービス紹介 Ver1.0株式会社デジカルメディア事業部 サービス紹介 Ver1.0
株式会社デジカルメディア事業部 サービス紹介 Ver1.0Digical Media
 
Server and Client side comparision
Server and Client side comparisionServer and Client side comparision
Server and Client side comparisionStew Duncan
 

En vedette (16)

Elk Canada
Elk CanadaElk Canada
Elk Canada
 
Lan2
Lan2Lan2
Lan2
 
Get Multiple Regression Assignment Help
Get Multiple Regression Assignment Help Get Multiple Regression Assignment Help
Get Multiple Regression Assignment Help
 
Satyam Scam
Satyam ScamSatyam Scam
Satyam Scam
 
Organizational Change
Organizational ChangeOrganizational Change
Organizational Change
 
Personal Memoir Slideshow
Personal Memoir SlideshowPersonal Memoir Slideshow
Personal Memoir Slideshow
 
Astra Gin, A Nu Liv Science Nutraceutical Ingredient For Increasing Nutrient ...
Astra Gin, A Nu Liv Science Nutraceutical Ingredient For Increasing Nutrient ...Astra Gin, A Nu Liv Science Nutraceutical Ingredient For Increasing Nutrient ...
Astra Gin, A Nu Liv Science Nutraceutical Ingredient For Increasing Nutrient ...
 
Horario 2012 1_electronica_yopal (1)
Horario 2012 1_electronica_yopal (1)Horario 2012 1_electronica_yopal (1)
Horario 2012 1_electronica_yopal (1)
 
"営業マン"な自社サイトを作る
"営業マン"な自社サイトを作る"営業マン"な自社サイトを作る
"営業マン"な自社サイトを作る
 
Nuliv An Overview Of Nu Liv Science 2010 6 21
Nuliv An Overview Of Nu Liv Science 2010 6 21Nuliv An Overview Of Nu Liv Science 2010 6 21
Nuliv An Overview Of Nu Liv Science 2010 6 21
 
System Programming - Threading
System Programming - ThreadingSystem Programming - Threading
System Programming - Threading
 
Horario 2012_ Ingeniería Electrónica
Horario 2012_ Ingeniería  Electrónica Horario 2012_ Ingeniería  Electrónica
Horario 2012_ Ingeniería Electrónica
 
Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715Fundamentals of Transport Phenomena ChE 715
Fundamentals of Transport Phenomena ChE 715
 
New England Business Expo 2009
New England Business Expo 2009New England Business Expo 2009
New England Business Expo 2009
 
株式会社デジカルメディア事業部 サービス紹介 Ver1.0
株式会社デジカルメディア事業部 サービス紹介 Ver1.0株式会社デジカルメディア事業部 サービス紹介 Ver1.0
株式会社デジカルメディア事業部 サービス紹介 Ver1.0
 
Server and Client side comparision
Server and Client side comparisionServer and Client side comparision
Server and Client side comparision
 

Similaire à Ruby Programming Assignment Help

golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdfSpam92
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmersMark Whitaker
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
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 basicsRasan Samarasinghe
 
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.pdfadcrates2010
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovyIsuru Samaraweera
 
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 GoMatt Stine
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 

Similaire à 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
 

Dernier

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 

Dernier (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 

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