This document provides information about methods and functional programming in Ruby. It defines what a method is, how methods are defined and invoked, and how they can return values. It discusses defining simple methods, method return values, singleton methods, and undefining methods. It also covers method name conventions, omitting parentheses in method calls, variable-length argument lists, default parameter values, and using hashes for named arguments. The document concludes by explaining procs and lambdas, how they are created, and how they are invoked differently than regular methods.
- Ruby is an object-oriented language where everything is an object and classes define methods that objects respond to.
- Classes can inherit and override methods from superclasses and include methods from modules.
- The initialize method is used as a constructor to initialize instance variables. Accessors provide access to instance variables.
- Common methods like +, -, *, [] can be defined for a class to allow arithmetic and array-like access to objects.
This document provides an overview of key concepts in Python including:
- Python is a dynamically typed language where variables are not explicitly defined and can change type.
- Names and identifiers in Python are case sensitive and follow specific conventions.
- Python uses indentation rather than brackets to define blocks of code.
- Core data types in Python include numeric, string, list, tuple, dictionary, set, boolean and file types. Each has specific characteristics and operators.
This document discusses code smells that indicate opportunities for refactoring, including duplicated code, long methods, long parameter lists, divergent change, and shotgun surgery. It provides examples of each smell and recommends corresponding refactoring techniques, such as extract method, extract class, introduce parameter object, replace parameter with method, move method, and move field, to improve code design, readability, and maintainability.
This document discusses file handling in C++. It introduces three classes - ofstream, ifstream, and fstream - that allow performing output and input of characters to and from files. The ofstream class is used to write to files, ifstream is used to read from files, and fstream can both read and write. The open() method is used to open a file, specifying the file name and optional file mode. Writing to a file uses the << operator and reading uses the >> operator. Operator overloading allows user-defined types like classes to define the meaning of operators like + when used on their objects.
This document provides an overview of object-oriented programming concepts in C++, including classes, objects, encapsulation, inheritance, polymorphism, and more. Key concepts are defined, such as classes containing data members and methods. Inheritance allows derived classes to inherit properties of base classes. Polymorphism allows calling the correct overridden method at runtime based on the object type. Virtual functions provide late binding so the correct derived class method is called.
StringBuffer implements a mutable sequence of characters that can be modified unlike strings. It has methods to modify the character sequence such as append, insert, delete and replace. It can grow dynamically as characters are added and its methods are used by the compiler to implement string concatenation with the + operator.
Regular expressions are a powerful tool for searching, parsing, and modifying text patterns. They allow complex patterns to be matched with simple syntax. Some key uses of regular expressions include validating formats, extracting data from strings, and finding and replacing substrings. Regular expressions use special characters to match literal, quantified, grouped, and alternative character patterns across the start, end, or anywhere within a string.
- Ruby is an object-oriented language where everything is an object and classes define methods that objects respond to.
- Classes can inherit and override methods from superclasses and include methods from modules.
- The initialize method is used as a constructor to initialize instance variables. Accessors provide access to instance variables.
- Common methods like +, -, *, [] can be defined for a class to allow arithmetic and array-like access to objects.
This document provides an overview of key concepts in Python including:
- Python is a dynamically typed language where variables are not explicitly defined and can change type.
- Names and identifiers in Python are case sensitive and follow specific conventions.
- Python uses indentation rather than brackets to define blocks of code.
- Core data types in Python include numeric, string, list, tuple, dictionary, set, boolean and file types. Each has specific characteristics and operators.
This document discusses code smells that indicate opportunities for refactoring, including duplicated code, long methods, long parameter lists, divergent change, and shotgun surgery. It provides examples of each smell and recommends corresponding refactoring techniques, such as extract method, extract class, introduce parameter object, replace parameter with method, move method, and move field, to improve code design, readability, and maintainability.
This document discusses file handling in C++. It introduces three classes - ofstream, ifstream, and fstream - that allow performing output and input of characters to and from files. The ofstream class is used to write to files, ifstream is used to read from files, and fstream can both read and write. The open() method is used to open a file, specifying the file name and optional file mode. Writing to a file uses the << operator and reading uses the >> operator. Operator overloading allows user-defined types like classes to define the meaning of operators like + when used on their objects.
This document provides an overview of object-oriented programming concepts in C++, including classes, objects, encapsulation, inheritance, polymorphism, and more. Key concepts are defined, such as classes containing data members and methods. Inheritance allows derived classes to inherit properties of base classes. Polymorphism allows calling the correct overridden method at runtime based on the object type. Virtual functions provide late binding so the correct derived class method is called.
StringBuffer implements a mutable sequence of characters that can be modified unlike strings. It has methods to modify the character sequence such as append, insert, delete and replace. It can grow dynamically as characters are added and its methods are used by the compiler to implement string concatenation with the + operator.
Regular expressions are a powerful tool for searching, parsing, and modifying text patterns. They allow complex patterns to be matched with simple syntax. Some key uses of regular expressions include validating formats, extracting data from strings, and finding and replacing substrings. Regular expressions use special characters to match literal, quantified, grouped, and alternative character patterns across the start, end, or anywhere within a string.
Core java by a introduction sandesh sharmaSandesh Sharma
This document provides an overview of core Java concepts including primitive types, wrappers, static methods and blocks, strings, abstract classes and interfaces, collections, equals and hashcode methods, and threads. It defines each concept, provides examples of usage, and notes key behaviors and properties. The document serves as a reference for fundamental Java programming concepts.
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Examshishamrizvi
The document provides an overview of key concepts in C++ including:
- Data types like int, char, float, and double
- Variables, constants, and escape sequences
- Operators like assignment, arithmetic, relational, and logical operators
- Control structures like if/else, switch, for, while, and do-while loops
- Functions like main(), exit(), get(), put(), and getline()
- Input/output streams like cin, cout, and file streams
The document covers fundamental C++ concepts to help prepare for board exams.
The document discusses the eight primitive data types in Java - boolean, char, byte, short, int, long, float, and double. It explains what each type is used for, their possible value ranges, and when to use each type. Key points covered include int being the preferred integer type, double the preferred real number type, and the importance of declaring variables before use and giving them initial values.
This document provides an overview of LINQ (Language Integrated Query) in 3 sentences or less:
LINQ allows querying over local collections and data sources by using language integrated query syntax or methods like Where, Select, and OrderBy. It relies on concepts like generics, delegates, lambda expressions, and extension methods to define query behaviors in a clean, readable way. Mastering LINQ requires understanding how these underlying concepts work and fit together to enable powerful querying capabilities.
The document provides an introduction to object-oriented programming concepts in C++ including objects, classes, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It then describes the structure of a C++ program including include files, class definitions, data declarations, member functions, and main functions. Finally, it discusses control structures in C++ including decision making statements like if/else and switch statements, looping statements like while, do-while and for loops, and functions.
This document discusses key concepts in Java programming including classes, methods, parameters, and invoking methods. It explains that a program consists of classes, a class contains methods, and a method contains statements. Methods can take parameters, which are initialized when the method is called and allow passing in values. Parameters act similarly to local variables but are declared in the method signature.
Python Advanced – Building on the foundationKevlin Henney
This is a two-day course in Python programming aimed at professional programmers. The course material provided here is intended to be used by teachers of the language, but individual learners might find some of this useful as well.
The course assume the students already know Python, to the level taught in the Python Foundation course: http://www.slideshare.net/Kevlin/python-foundation-a-programmers-introduction-to-python-concepts-style)
The course is released under Creative Commons Attribution 4.0. Its primary location (along with the original PowerPoint) is at https://github.com/JonJagger/two-day-courses/tree/master/pa
This document discusses various data types in programming languages including primitive, string, array, record, union, and pointer types. It provides details on how each type is defined and implemented in different languages. Primitive types include integers, floats, decimals, booleans, characters. Strings can have static or dynamic lengths. Arrays can be static, dynamic and allow various index types and initialization. Records group heterogeneous data under field names. Unions allow storing different types in a variable. Pointers provide indirect addressing but require careful use to avoid dangling references.
Object Oriented Programming using C++ Part IIIAjit Nayak
The document discusses inheritance in object-oriented programming. It defines inheritance as a technique where a new subclass inherits attributes and behaviors from an existing superclass without needing to redefine them. This allows code reuse and reduces development costs. The document provides examples of single inheritance with classes like Employee and Manager, and multi-level inheritance with Student, Test, and Result classes. It also discusses polymorphism through method overriding and different types of inheritance like public, private and protected.
This document provides an introduction to object oriented programming with C++. It discusses key concepts such as data types, operators, functions, input/output streams, and classes. Sample code is provided to demonstrate basic C++ syntax and structure, including comments, preprocessor directives, namespaces, the main function, and use of cout and cin for output and input. Functions are described as blocks of code that are called by name, with arguments allowed to pass parameters. The main benefits of C++ compared to C are noted as handling increasing complexity through use of classes.
This chapter discusses objects, classes, and input/output in Java. It covers defining objects and reference variables, using predefined classes and methods, the String class, input/output dialog boxes, formatting output, parsing numeric strings, and file input/output. Key topics include declaring and instantiating objects, calling methods, reading/writing to files, and handling exceptions during input/output operations.
This document provides an introduction to Python fundamentals. It discusses Python's character set, tokens or lexical units including keywords, identifiers, literals, operators, and punctuators. It also covers Python programming concepts such as variables and assignments, functions, comments, statements, and programming conventions regarding whitespace, maximum line length, and case sensitivity. The document aims to explain the basic building blocks of the Python language to learn Python programming.
The document provides an overview of Strings and StringBuilders in Java. It discusses Strings as immutable objects and how StringBuilders can be more efficient for modifying strings. It also covers common String and StringBuilder methods, when to use each, and exceptions in Java using try/catch blocks.
The Ring programming language version 1.5.3 book - Part 187 of 194Mahmoud Samir Fayed
This document summarizes key aspects of Ring programming language functions and objects. It explains that when a new object is created, the class region code is executed to initialize attributes. Methods are collected from the class and its parents. Attributes can be accessed directly or via getter/setter methods. Global names are searched when defining class attributes to allow flexibility, though this could cause conflicts. The document provides examples of optional and default parameters in functions using a list, and how to print only keys or values from a list. It also explains newline printing behavior with lists.
This document proposes a new approach for ontology alignment extraction that generates mapping hypotheses between ontological entities and equivalence assumptions about linguistic entities, and defines a joint optimization problem to keep the linguistic and mapping assumptions consistent using Markov Logic. It describes generating token and label similarities, representing the relationships between tokens, labels and entities as weighted formulas, and using logical rules and reasoning to select the optimal consistent alignment. The approach is evaluated on the OAEI conference track, demonstrating good results but also limitations regarding runtime and parameterization that need further work to develop it into a robust matching system.
This document discusses text and numbers in programming. It covers defining and manipulating text strings using single or double quotes. Escape characters can be used inside strings. Text can be validated and formatted using various string functions like trim(), strlen(), strtoupper(), substr(), and str_replace(). Numbers can be integers or floats. Variables hold data and can be operated on with arithmetic and assignment operators like +, -, *, /, %, and .=. Variables can also be incremented, decremented, and placed inside strings.
This chapter provides a brief overview of some core aspects of the C# programming language, including namespaces, classes, attributes, interfaces, enums, structs, and methods. It explains how namespaces organize related classes and avoid name collisions. It describes the structure of classes, their members, modifiers, and inheritance. It also covers attributes, interfaces, enums, structs, and how methods can be defined as virtual or overridden.
This document provides a summary of key concepts in Ruby including:
- Everything is an object in Ruby including true, false, nil
- Classes are defined using class, modules using module, and objects are created using Object.new
- Methods are defined using def, variables can have default values, and returns are not required
- Modules contain reusable code that can be included in classes
- Classes can inherit from other classes and modules can be mixed in
Ruby methods are used to bundle repeatable statements into a single unit. Method names should begin with a lowercase letter. Methods should be defined before calling them. Methods can accept parameters with default values. Variables can be returned from methods. The return statement is used to return values explicitly. Methods can take a variable number of parameters using *. Class methods can be accessed without instantiating an object. The alias statement creates an alias for a method or variable. The undef statement cancels a method definition.
1. A class is a blueprint for objects that defines common properties and methods. It can include modifiers, name, superclass/interfaces, and a class body.
2. An object is created using the new keyword, assigning the object to a reference variable. Reference variables store an object's address in memory. Assigning one reference variable to another does not create distinct copies but points to the same object.
3. A method performs a specific task and can return a result. It includes modifiers, return type, name, parameters, and a method body. Method overloading allows methods with the same name but different parameters.
The document summarizes key concepts in Ruby including expressions, operators, literals, variables, constants, method invocations, assignments, and parallel assignments. Expressions can be combined with operators and evaluated to produce values. Variables, constants, literals, and keywords also evaluate to values that can be used in expressions. Methods are invoked by sending messages to objects and can accept arguments. Assignments are used to set values to variables, attributes, and array elements. Parallel assignments allow setting multiple variables at once.
Core java by a introduction sandesh sharmaSandesh Sharma
This document provides an overview of core Java concepts including primitive types, wrappers, static methods and blocks, strings, abstract classes and interfaces, collections, equals and hashcode methods, and threads. It defines each concept, provides examples of usage, and notes key behaviors and properties. The document serves as a reference for fundamental Java programming concepts.
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Examshishamrizvi
The document provides an overview of key concepts in C++ including:
- Data types like int, char, float, and double
- Variables, constants, and escape sequences
- Operators like assignment, arithmetic, relational, and logical operators
- Control structures like if/else, switch, for, while, and do-while loops
- Functions like main(), exit(), get(), put(), and getline()
- Input/output streams like cin, cout, and file streams
The document covers fundamental C++ concepts to help prepare for board exams.
The document discusses the eight primitive data types in Java - boolean, char, byte, short, int, long, float, and double. It explains what each type is used for, their possible value ranges, and when to use each type. Key points covered include int being the preferred integer type, double the preferred real number type, and the importance of declaring variables before use and giving them initial values.
This document provides an overview of LINQ (Language Integrated Query) in 3 sentences or less:
LINQ allows querying over local collections and data sources by using language integrated query syntax or methods like Where, Select, and OrderBy. It relies on concepts like generics, delegates, lambda expressions, and extension methods to define query behaviors in a clean, readable way. Mastering LINQ requires understanding how these underlying concepts work and fit together to enable powerful querying capabilities.
The document provides an introduction to object-oriented programming concepts in C++ including objects, classes, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It then describes the structure of a C++ program including include files, class definitions, data declarations, member functions, and main functions. Finally, it discusses control structures in C++ including decision making statements like if/else and switch statements, looping statements like while, do-while and for loops, and functions.
This document discusses key concepts in Java programming including classes, methods, parameters, and invoking methods. It explains that a program consists of classes, a class contains methods, and a method contains statements. Methods can take parameters, which are initialized when the method is called and allow passing in values. Parameters act similarly to local variables but are declared in the method signature.
Python Advanced – Building on the foundationKevlin Henney
This is a two-day course in Python programming aimed at professional programmers. The course material provided here is intended to be used by teachers of the language, but individual learners might find some of this useful as well.
The course assume the students already know Python, to the level taught in the Python Foundation course: http://www.slideshare.net/Kevlin/python-foundation-a-programmers-introduction-to-python-concepts-style)
The course is released under Creative Commons Attribution 4.0. Its primary location (along with the original PowerPoint) is at https://github.com/JonJagger/two-day-courses/tree/master/pa
This document discusses various data types in programming languages including primitive, string, array, record, union, and pointer types. It provides details on how each type is defined and implemented in different languages. Primitive types include integers, floats, decimals, booleans, characters. Strings can have static or dynamic lengths. Arrays can be static, dynamic and allow various index types and initialization. Records group heterogeneous data under field names. Unions allow storing different types in a variable. Pointers provide indirect addressing but require careful use to avoid dangling references.
Object Oriented Programming using C++ Part IIIAjit Nayak
The document discusses inheritance in object-oriented programming. It defines inheritance as a technique where a new subclass inherits attributes and behaviors from an existing superclass without needing to redefine them. This allows code reuse and reduces development costs. The document provides examples of single inheritance with classes like Employee and Manager, and multi-level inheritance with Student, Test, and Result classes. It also discusses polymorphism through method overriding and different types of inheritance like public, private and protected.
This document provides an introduction to object oriented programming with C++. It discusses key concepts such as data types, operators, functions, input/output streams, and classes. Sample code is provided to demonstrate basic C++ syntax and structure, including comments, preprocessor directives, namespaces, the main function, and use of cout and cin for output and input. Functions are described as blocks of code that are called by name, with arguments allowed to pass parameters. The main benefits of C++ compared to C are noted as handling increasing complexity through use of classes.
This chapter discusses objects, classes, and input/output in Java. It covers defining objects and reference variables, using predefined classes and methods, the String class, input/output dialog boxes, formatting output, parsing numeric strings, and file input/output. Key topics include declaring and instantiating objects, calling methods, reading/writing to files, and handling exceptions during input/output operations.
This document provides an introduction to Python fundamentals. It discusses Python's character set, tokens or lexical units including keywords, identifiers, literals, operators, and punctuators. It also covers Python programming concepts such as variables and assignments, functions, comments, statements, and programming conventions regarding whitespace, maximum line length, and case sensitivity. The document aims to explain the basic building blocks of the Python language to learn Python programming.
The document provides an overview of Strings and StringBuilders in Java. It discusses Strings as immutable objects and how StringBuilders can be more efficient for modifying strings. It also covers common String and StringBuilder methods, when to use each, and exceptions in Java using try/catch blocks.
The Ring programming language version 1.5.3 book - Part 187 of 194Mahmoud Samir Fayed
This document summarizes key aspects of Ring programming language functions and objects. It explains that when a new object is created, the class region code is executed to initialize attributes. Methods are collected from the class and its parents. Attributes can be accessed directly or via getter/setter methods. Global names are searched when defining class attributes to allow flexibility, though this could cause conflicts. The document provides examples of optional and default parameters in functions using a list, and how to print only keys or values from a list. It also explains newline printing behavior with lists.
This document proposes a new approach for ontology alignment extraction that generates mapping hypotheses between ontological entities and equivalence assumptions about linguistic entities, and defines a joint optimization problem to keep the linguistic and mapping assumptions consistent using Markov Logic. It describes generating token and label similarities, representing the relationships between tokens, labels and entities as weighted formulas, and using logical rules and reasoning to select the optimal consistent alignment. The approach is evaluated on the OAEI conference track, demonstrating good results but also limitations regarding runtime and parameterization that need further work to develop it into a robust matching system.
This document discusses text and numbers in programming. It covers defining and manipulating text strings using single or double quotes. Escape characters can be used inside strings. Text can be validated and formatted using various string functions like trim(), strlen(), strtoupper(), substr(), and str_replace(). Numbers can be integers or floats. Variables hold data and can be operated on with arithmetic and assignment operators like +, -, *, /, %, and .=. Variables can also be incremented, decremented, and placed inside strings.
This chapter provides a brief overview of some core aspects of the C# programming language, including namespaces, classes, attributes, interfaces, enums, structs, and methods. It explains how namespaces organize related classes and avoid name collisions. It describes the structure of classes, their members, modifiers, and inheritance. It also covers attributes, interfaces, enums, structs, and how methods can be defined as virtual or overridden.
This document provides a summary of key concepts in Ruby including:
- Everything is an object in Ruby including true, false, nil
- Classes are defined using class, modules using module, and objects are created using Object.new
- Methods are defined using def, variables can have default values, and returns are not required
- Modules contain reusable code that can be included in classes
- Classes can inherit from other classes and modules can be mixed in
Ruby methods are used to bundle repeatable statements into a single unit. Method names should begin with a lowercase letter. Methods should be defined before calling them. Methods can accept parameters with default values. Variables can be returned from methods. The return statement is used to return values explicitly. Methods can take a variable number of parameters using *. Class methods can be accessed without instantiating an object. The alias statement creates an alias for a method or variable. The undef statement cancels a method definition.
1. A class is a blueprint for objects that defines common properties and methods. It can include modifiers, name, superclass/interfaces, and a class body.
2. An object is created using the new keyword, assigning the object to a reference variable. Reference variables store an object's address in memory. Assigning one reference variable to another does not create distinct copies but points to the same object.
3. A method performs a specific task and can return a result. It includes modifiers, return type, name, parameters, and a method body. Method overloading allows methods with the same name but different parameters.
The document summarizes key concepts in Ruby including expressions, operators, literals, variables, constants, method invocations, assignments, and parallel assignments. Expressions can be combined with operators and evaluated to produce values. Variables, constants, literals, and keywords also evaluate to values that can be used in expressions. Methods are invoked by sending messages to objects and can accept arguments. Assignments are used to set values to variables, attributes, and array elements. Parallel assignments allow setting multiple variables at once.
This document discusses object-oriented programming concepts in Objective-C such as classes, inheritance, polymorphism, and exceptions. It covers creating interface and implementation files, using properties and methods, inheritance hierarchies with subclasses, overriding methods, abstract classes, polymorphism through dynamic binding, and exceptions. Key topics include creating .h and .m files to define a class, using self to reference the current object, returning objects from methods, and extending classes through inheritance while allowing method overriding.
This document discusses delegates in C#, which are similar to function pointers in C/C++. Delegates allow methods to be passed as arguments and stored for later invocation. The document explains that delegates store references to methods, can reference static or instance methods, and are type-safe. It also covers declaring delegates, instantiating delegates by storing method references, and using single-cast versus multi-cast delegates which can store references to multiple methods and invoke them in sequence.
This document discusses delegates in C#, which are similar to function pointers in C/C++. Delegates allow methods to be passed as arguments and stored for later invocation. The document explains that delegates store references to methods, can reference static or instance methods, and are type-safe. It also covers declaring delegates, instantiating delegates by storing method references, and using single-cast versus multi-cast delegates which can store references to multiple methods and invoke them in sequence.
Metaprogramming involves writing code that manipulates language constructs and generates or modifies code at runtime. This allows developers to define domain-specific languages, remove duplications, and enhance Ruby's core functionality. Everything in Ruby is an object, including classes and modules. Metaprogramming techniques like monkey patching, dynamic methods, and refinements allow modifying classes and modules at runtime. However, metaprogramming should be avoided when possible, as it can reduce code readability and maintainability.
This document introduces lambda expressions in Java 8. It provides background on why lambda expressions were added to Java, including to allow for more functional programming and parallel processing. It covers the syntax of lambda expressions, when they should and should not be used, functional interfaces, method and constructor references, referencing external variables, debugging lambda expressions, and new lambda methods added in Java 8. The document also advertises exercises for the reader to complete to practice using lambda expressions.
This document provides an overview of SAX and DOM, which are APIs for parsing XML documents. It discusses:
- SAX and DOM are standards for XML parsers that allow reading and interpreting XML files. SAX is event-based and reads XML sequentially, while DOM loads the entire XML document into memory allowing random access.
- SAX works through callbacks, where the parser calls methods supplied by the application to handle events like start elements, end elements, and character data.
- A simple SAX program is demonstrated using two classes - one contains the main method and parses the XML, while the other implements handler callbacks.
- Key differences between SAX and DOM are that DOM provides random access to
Slides aim to provide constructed information about functional programming in Java 8. To able to do that, Lambdas, Built-in Functional Interfaces and Optionals summarised with code examples.
CIS 1403 lab 3 functions and methods in JavaHamad Odhabi
This lab discusses and provides examples of both built-in and user-defined functions. In Java function are referred to as methods. Therefore, in the rest of this lab, the term methods will be used to refer to functions. The lab will cover the type of methods, naming of functions, the scope of variables and recursion.
The Ring programming language version 1.10 book - Part 86 of 212Mahmoud Samir Fayed
- When calling a function or method in Ring, it will search scopes in this order: methods, user-defined functions, standard/C functions.
- This avoids conflicts between functions and methods with the same name.
- Functions can be replaced by other functions or methods.
- The self.method() syntax is not necessary but this.method() can escape the current object scope.
This document discusses code smells and refactoring techniques. It describes various code smells that can occur including bloaters, object-oriented abusers, change preventers, dispensables, and couplers. For each smell, examples are provided and potential refactoring techniques are suggested to improve the code design by reducing coupling and improving cohesion.
chap 6 : Objects and classes (scjp/ocjp)It Academy
.1 Develop code that declares classes (including abstract
and all forms of nested classes), interfaces, and enums,
and includes the appropriate use of package and import
statements (including static imports).
1.4 Develop code that declares both static and non-static
methods, and - if appropriate - use method names that
adhere to the JavaBeans naming standards. Also develop
code that declares and uses a variable-length argument list.
1.5 Given a code example, determine if a method is correctly
overriding or overloading another method, and identify
legal return values (including covariant returns), for the
method.
1.6 Given a set of classes and superclasses, develop
constructors for one or more of the classes. Given a
class declaration, determine if a default constructor will
be created, and if so, determine the behavior of that
constructor. Given a nested or non-nested class listing,
write code to instantiate the class.
5.1 Develop code that implements tight encapsulation,
loose coupling, and high cohesion in classes, and describe
the benefits.
5.2 Given a scenario, develop code that demonstrates the
use of polymorphism. Further, determine when casting will
be necessary and recognize compiler vs. runtime errors
related to object reference casting.
5.3 Explain the effect of modifiers on inheritance with
respect to constructors, instance or static variables, and
instance or static methods.
Ruby's method_missing method allows developers to override Ruby's default method lookup behavior when a method is not found. This is commonly used to create domain-specific languages in Ruby. When Ruby cannot find a method, it will call method_missing as a last resort. Developers can define method_missing to customize what happens in this case.
The document provides an overview of the course curriculum for a Python with AI session. It covers Python basics, pandas for working with datasets, REST APIs and GitHub, data visualization, and a final project. It also reviews key Python concepts like conditionals, loops, lists, dictionaries, modules, and the pandas library for reading CSV files and working with dataframes. Exercises include generating random numbers and working with lists, dictionaries, and dataframes.
This document discusses method overloading in Java. It defines a method as a collection of statements that perform an operation. A method has a header specifying its modifiers, return type, name, and parameters. The body contains the statements. Method overloading allows multiple methods with the same name but different signatures. Signatures can vary by parameter types, numbers, or orders. Overloaded methods use static binding at compile time. The example shows two Addition methods differentiated by an extra parameter, with the correct one called based on arguments.
Similar to 7 Methods and Functional Programming (20)
Rails is a web application framework written in Ruby that makes programming web applications easier. The key principles of Rails are DRY (Don't Repeat Yourself), convention over configuration, and using RESTful architecture. Rails uses the MVC pattern with models representing data, views representing the user interface, and controllers handling requests and passing data between models and views. Creating a Rails application involves generating the app, setting up the database schema through migrations, and using validations and callbacks to control object state changes.
This document discusses Ruby gems, including:
- How to interact with gems using the gem command to search, install, uninstall, list, and view documentation for gems.
- The standard structure for gems including code, tests, documentation, and a gemspec file.
- How to create your own gem including naming conventions, building a gemspec, and publishing the gem to RubyGems.org.
Deepak H B provides contact information and an overview of networking in Ruby. Ruby uses sockets for networking rather than core classes. Sockets allow reading and writing data to other computers like files. Simple client and server examples are provided using TCPSocket and TCPServer classes. Datagrams can also be used with UDPSocket for lower overhead communication. Multiplexing servers are discussed that allow serving multiple clients simultaneously using Kernel.select. Finally, prebuilt libraries are mentioned for implementing protocols like HTTP, FTP, SMTP, POP and IMAP.
The document discusses Ruby's input and output capabilities. It covers:
- Ruby provides two interfaces for I/O - simple print/gets methods and more advanced methods in the Kernel module.
- All I/O is handled by the IO base class, which File and BasicSocket subclass. IO objects represent bidirectional channels between Ruby and external resources.
- Files can be opened for reading, writing or both using File.new/File.open, specifying a mode. File streams support various methods for reading and writing lines and bytes.
- Random access methods like pos, tell, seek allow reading/writing specific locations in files and strings.
This document provides an introduction to exception handling in Ruby. It defines what exceptions are and how they are raised when errors occur. It describes how to handle exceptions using rescue clauses and how to define custom exception classes. It also covers different ways to raise exceptions and additional exception handling concepts like ensure clauses.
This document provides an overview of control structures and flow altering statements in Ruby. It discusses conditionals like if/else, unless, case; loops like while, until, for/in; iterators and enumerable objects; and flow altering statements like return, break, next, redo. Conditionals and loops allow altering the sequential execution of code. Iterators and enumerables provide concise ways to iterate over objects. Statements like return and break change the normal flow of control.
This document provides information about various data types in Ruby including numbers, text, arrays, hashes, and more. It discusses how numbers can be integers, floats, complexes, big decimals, and rationals. It also covers string literals and interpolation, character literals, and various string operators and methods. Arrays and hashes are introduced as mutable collections that can hold heterogeneous data and are accessed via indexes.
Deepak H B is a web application developer who specializes in Ruby on Rails. He provides his contact information including email and LinkedIn profile. The document then discusses installing Ruby through different methods like RVM, basics of using RVM to manage Ruby versions and gems, and how to run Ruby code interactively through IRB or by creating Ruby program files. It also briefly mentions Ruby documentation tools like RDoc and RI.
Walmart Business+ and Spark Good for Nonprofits.pdfTechSoup
"Learn about all the ways Walmart supports nonprofit organizations.
You will hear from Liz Willett, the Head of Nonprofits, and hear about what Walmart is doing to help nonprofits, including Walmart Business and Spark Good. Walmart Business+ is a new offer for nonprofits that offers discounts and also streamlines nonprofits order and expense tracking, saving time and money.
The webinar may also give some examples on how nonprofits can best leverage Walmart Business+.
The event will cover the following::
Walmart Business + (https://business.walmart.com/plus) is a new shopping experience for nonprofits, schools, and local business customers that connects an exclusive online shopping experience to stores. Benefits include free delivery and shipping, a 'Spend Analytics” feature, special discounts, deals and tax-exempt shopping.
Special TechSoup offer for a free 180 days membership, and up to $150 in discounts on eligible orders.
Spark Good (walmart.com/sparkgood) is a charitable platform that enables nonprofits to receive donations directly from customers and associates.
Answers about how you can do more with Walmart!"
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
3. Introduction
• A method is a named block of parameterized code associated with one or
more objects.
• A method invocation specifies the method name and the object on which
the method is invoked.
• The value of the last expression evaluated in the method becomes the
value of the method invocation expression.
• Ruby is purely object oriented language, all the methods are associated
with at least one object.
• Methods are the fundamental part of Ruby’s syntax, but they are not
values that Ruby programs can operate on.
• Methods are not Ruby’s only form of parameterized executable code,
Blocks are also executable chunks of code and may have parameters.
4. Defining Simple Method
• Methods are defined with the def keyword.
• This is followed by the method name and optional list of parameter names
in parentheses.
• The Ruby code constitutes the method body follows the parameter list
and end of the method is marked with the end keyword.
• Parameter names can be used as variables within the method body and
the values of these named parameters come from the arguments to a
method invocation.
def method_name(n)
#method body
End
• Methods are always invoked on an object.
• Ruby uses “.” to separate the object from the method to be invoked on it.
5. Method Return Value
• Methods may be terminated normally or abnormally.
Abnormal termination occurs when the method raises an exception.
• The return keyword is used to force a return prior to the end of the
method.
• The expression follows the return keyword is evaluated and returned.
• The nil is returned if there is no expression.
• Ruby methods may return more than one value by using return keyword
explicitly
def return_numbers
return 1,2,3
end
• More than one return values are collected into an array and it becomes
the single return value of the method.
• Methods of this form are typically intended for use with parallel
assignment.
x,y,z = return_numbers
6. Singleton Methods
• The methods that are defined for single specified object are called
singleton methods.
• Simply follow the def keyword with an object that follows by a period and
the name of the method to be defined.
o = “message”
def o.printme
puts self
end
o.printme # “message”
• Class methods such as Math.sin and File.delete are actually singleton
methods.
• Math is constant that refers to a Module object and File is a constant that
refers to a Class object.
• Ruby implementation typically treat Fixnum and Symbol values as
immediate values rather than as true object reference. For this reason
singleton methods may not be defined on Fixnum and Symbol.
7. Undefining Methods
• Methods are defined with the def keyword and may be
undefined using undef keyword.
• undef can be used to undefined inherited methods without
affecting the definition of the method in the class form which
it is inherited.
• This is not commonly used statement.
• This should followed by a single identifier that specifies the
method name.
• It cannot be used to undefine a singleton methods.
8. Method Name
• Method names begin with lower case letters.
• If method name is longer than one word, the usual
convention is to separate the words with underscores
like_this.
• Method names might end with an equal sign, a question
mark, or an exclamation point.
• The equal sign suffix signifies that the method is setter.
• The question mark signifies that method returns a value that
answers question posed by the method invocation.
empty?
9. Contd..
• Methods whose names are ending with exclamation mark should be used
with caution.
sort!, exit!
• Methods ending with exclamation mark are mutators, which alters the
internal state of an object.
• Ruby’s operators, such as +, * and even the array index [] operator are
implemented with methods that you can define in your own class.
def +(other)
self.concatenate(other)
end
• Ruby can define more than one name for same method.
• The language ahs alias key word to define a new name for existing
method.
alias to_str, to_s #alias new_name existing_name
• This can be used inside the class whose methods needs to be renamed.
10. Methods and Parentheses
• Ruby allows parentheses to be omitted from most of the method
invocations.
puts “Hello world”
puts(“Hello world”)
• The next example
greeting = “Hello”
size = greeting.length
• Normally length looks like property, field or variable of string
objects. But this is method invocation. Then length method expects
no arguments and is invoked without parentheses.
size = greeting.length()
11. Contd..
• Parentheses are very commonly omitted when there are zero
or one arguments to the invoked methods.
• Parentheses may also be omitted around the parameter list in
method definitions, though it is hard to argue that this makes
your code clearer or more readable.
• Some code is ambiguous if the parentheses are omitted and
here Ruby requires that you include them.
• The most common case is nested method invocations of the
form f g x,y. In Ruby, invocations of that form mean f(g(x,y))
12. Method Arguments
• Simple method declarations include a comma-separated list
of names after the method name.
• But there is much more to Ruby’s method arguments:
– How to declare an arguments that has a default value.
– How to declare a method that accepts any number of
arguments.
– How to simulate named method arguments with special
syntax for passing a hash to a method.
13. Parameter Defaults
• When you define a method, you can specify default values for some or all
of the parameters.
def prefix(s, len=1)
S[0,len]
end
• The above methods defines two parameters, but the second on has a
default value. This can be invoked as below:
prefix(“ruby”, 3) #=> “rub”
prefix(“Ruby”) #=> “R”
• Parameter defaults are evaluated when a method is invoked rather than
when it is parsed. In the following method, the default value [] produces a
new empty array on each invocation.
def append(x, a=[])
a<<x
end
14. Contd..
• In Ruby 1.8, method parameters with default values must
appear after all ordinary parameters in the parameter list.
• In Ruby 1.9, allows ordinary parameters to appear after the
parameters with defaults. But mixing between these two
parameters are not allowed.
15. Variable-Length Argument Lists and
Arrays
• The * is put before one of the methods parameter to accept an arbitrary
number of arguments.
def max(first, *rest)
max = first
rest.each{|x| max = x if x > maz}
max
end
• The max method requires at least one argument, but it may accept any
number of additional arguments.
max(1) # first=1, rest=[]
max(1,2)# first=1, rest=[2]
max[1,2,3] #first=1, rest=[2,3]
16. Contd..
• No more than one argument is prefixed with *.
• This should be the last parameter of a method.
• The max method can also accept single array as argument by using
splat (*) operator on invocation. This will expand the elements of an
array.
data = [3,2,1]
max(*data)
17. Hashes for Named Arguments
• When a method accepts more than two or three arguments, it will be
difficult for the programmer invoking the method to remember the proper
order.
• The solution for this is to write a method that accepts hash a parameter.
def sequence(args)
n=args[:n] || 0
m=args[:m] || 1
c=args[:c] ||0
end
• This method can be invoked with hash literal as argument
sequence({:n=>3, :m=>5})
• Ruby supports to pass hash without curly braces to the last argument of
the method.
sequence(:n=>3, :m=>5)
• If parenthesis are omitted, then curly braces must be omitted as well.
sequence {:n=>2, :m=>5} # Syntax error
18. Procs and Lambdas
• Blocks are syntactic structures in Ruby; they are not objects
and cannot be manipulated as object.
• It is possible, however to create an object that represents a
block.
• Depending on how the object is created it is called a proc
or lambda.
• Proc have block-like behavior and lambda’s have method-
like behavior.
• Both Proc and lambdas are instance of class Proc.
19. Creating Procs
• The Proc object is created by associating a block with a method that is
defined with an ampersand-prefixed block argument.
def makeproc(&p)
p
End
• With a makeproc method like this defined, we can create a Proc object by
adder = makeproc {|x,y| x+y}
• Now the variable adder refers to the Proc object. All proc objects have a
call method that when invoked runs the code contained in the block from
which proc was created.
sum = adder.call(2,2)
20. Proc.new
• This is the normal new method that most classes support, and it’s the
most obvious way to create a new instance of the Proc class.
• Proc.new expects no arguments and returns the instance of Proc class (not
lambda).
p = Proc.new {|x,y| x+y}
Kernel.lambda
• Another technique for creating Proc objects is with the lambda method.
• The lambda is a method of the kernel module, so it behaves like a global
function.
• The proc object returned from this method is a lambda rather than a proc.
• lambda expects no arguments, but there must be a block associated with
the invocation.
is_positive = lambda {|x| x>0}
21. Lambda Literals
• The created lambda method below
succ = lambda{|x| x+1}
• Can be converted to literal as follows:
– Replace the method name lambda with the punctuation -
>.
– Move the list of arguments outside of and just before the
curly braces.
– Change the argument list delimiters from || or ().
• With these the lambda literal
succ = ->(x){ x+1 }
22. Invoking Procs and Lambdas
• Procs and lambdas are objects, not methods and they cannot be invoked in the
same way that methods.
• If p is Proc object, it cannot invoked as method instead it can invoke the method of
p.
• Proc class defines a method named call.
• Invoking this method executes the code in the original block with the arguments
that are passed by call.
f = Proc.new{|x,y|1.0/(1.0/x+1.0/y)}
z = f.call(x,y)
• The Proc class also defines the array access operator to work the same way as call.
z = f[x,y]
• An additional way to invoke a Proc object as an alternative to square brackets, you
can use parenthesis prefixed with a period
z = f.(x,y)
23. The Arity of a Proc
• The arity of a proc or lambda is the number of arguments it expects.
• Proc object have an arity method that returns the number of arguments
they expect.
lambda{||}.arity # => 0
lambda{|x|}.arity # => 1
lambda{|x,y|}.arity # => 2
• The notion of arity gets confusing, when a Proc accepts an arbitrary
number of arguments in an * prefixed final argument.
• When Proc allows optional arguments, the arity method returns a
negative number of the form –n-1.
lambda{|*args|}.arity # => -1. ~-1 = -(-1)-1 = 0 arguments
required
lambda{|first, *rest|}.arity # => -2. ~-2 = -(-2)-1 = 1 argument
required
24. Proc Equality
• The Proc class defines an == method to determine whether two Proc
objects are equal.
• It is important to understand, however, that merely having the same
source code is not enough to make two procs or lambdas equal to each
other.
lambda{|x| x*x} == lambda{|x| x*x} #=> false
• The == method only returns true if on Proc is a clone or duplicate of the
other
p = lambda{|x| x*x}
q = p.dup
p == q # => true
p.object_id == q.object_id # => false
25. Functional Programming
• Ruby is not Functional programming language in the way that
languages like Lisp and Hskell are.
• Any time you use a block with an Enumerable iterators like
map or inject, your programming in a functional style.
mean = a.inject{|x,y| x+y}/a.size
sumOfSquares = a.map{|x| (x-mean)**2}.inject{|x,y| x+y}
26. Applying a Function to an Enumerable
• The map and inject are two of the most important iterators
defined by Enumerable.
• If we write a programs in a function-centric way, we might
like methods on our functions that allow us to apply those
functions to a specified Enumerable object.
27. # This module defines methods and operators for functional programming.
module Functional
# Apply this function to each element of the specified Enumerable,
# returning an array of results. This is the reverse of Enumerable.map.
# Use | as an operator alias. Read "|" as "over" or "applied over".
# Example:
# a = [[1,2],[3,4]]
# sum = lambda {|x,y| x+y}
# sums = sum|a # => [3,7]
def apply(enum)
enum.map &self
end
alias | apply
# Use this function to "reduce" an enumerable to a single quantity.
# This is the inverse of Enumerable.inject.
# Use <= as an operator alias.
# Mnemonic: <= looks like a needle for injections
# Example:
# data = [1,2,3,4]
# sum = lambda {|x,y| x+y}
# total = sum<=data # => 10
def reduce(enum)
enum.inject &self
end
alias <= reduce
end
28. • Notice that we define methods in a module named Functional, and when
we include this module into both the Proc and Method classes.
• Most of the methods that follow also define methods in this Functional
module, so that they work for both Proc and Method.
• With apply and reduce defined as above, we could refactor our statistical
computations as follows:
sum = lambda{|x,y| x+y} #A function to add two numbers
mean = (sum<=a)/a.size #Or sum.reduce(a) or a.inject(&sum)
deviation = lambda{|x| x-mean} #Function to compute difference from mean
square = lambda{|x| x*x} #Function to square a number
standardDeviation = Math.sqrt((sum<=square|(deviation|a))/(a.size-1))
Contd..
# Add these functional programming methods to Proc and
Method classes.
class Proc; include Functional; end
class Method; include Functional; end
29. Composing Functions
• If we have a functions f and g, we sometimes want to
define a new function h which is f(g()) or f composed with
g.
• We define a method that performs function composition
automatically.
30. module Functional
# Return a new lambda that computes self[f[args]].
# Use * as an operator alias for compose.
# Examples, using the * alias for this method.
# f = lambda {|x| x*x }
# g = lambda {|x| x+1 }
# (f*g)[2] # => 9
# (g*f)[2] # => 5
# def polar(x,y)
# [Math.hypot(y,x), Math.atan2(y,x)]
# end
# def cartesian(magnitude, angle)
# [magnitude*Math.cos(angle), magnitude*Math.sin(angle)]
# end
# p,c = method :polar, method :cartesian
# (c*p)[3,4] # => [3,4]
def compose(f)
if self.respond_to?(:arity) && self.arity == 1
lambda {|*args| self[f[*args]] }
else
lambda {|*args| self[*f[*args]] }
end
end
31. Contd..
• The example code in the comment demonstrates the use of
compose with Method objects as well as lambdas.
• We can use this new * function composition operator so slightly
simplify our computation of standard deviation.
standardDeviation = Math.sqrt((sum<=square*deviation|a)/(a.size-1))
• The difference is that we compose square and deviation into a
single function before applying it to the array a.
32. Partially Applying Functions
• In functional programming, partial application is the process of
taking a function and a partial set of argument values and
producing a new function that is equivalent to the original function
with the specified arguments fixed.
• For example,
$product = lambda {|x, y| x*y} #A function of two arguments
$double = lambda {|x| product(2,x) } #Apply one argument
• Partial application can be simplified with appropriate methods in
our Functional module.
33. module Functional
# Return a lambda equivalent to this one with one or more initial
# arguments applied. When only a single argument
# is being specified, the >> alias may be simpler to use.
# Example:
# product = lambda {|x,y| x*y}
# doubler = lambda >> 2
def apply_head(*first)
lambda {|*rest| self[*first.concat(rest)]}
end
# Return a lambda equivalent to this one with one or more final arguments
# applied. When only a single argument is being specified,
# the << alias may be simpler.
# Example:
# difference = lambda {|x,y| x-y }
# decrement = difference << 1
def apply_tail(*last)
lambda {|*rest| self[*rest.concat(last)]}
end
# Here are operator alternatives for these methods. The angle brackets
# point to the side on which the argument is shifted in.
alias >> apply_head # g = f >> 2 -- set first arg to 2
alias << apply_tail # g = f << 2 -- set last arg to 2
end
34. Contd..
• Using these methods and operators, we can define our double
function simply as product >> 2.
• We can use partial application to make our standard deviation
computation somewhat more abstract, by building our deviation
function from more general purpose difference function.
difference = lambda {|x,y| x-y} #Compute difference of two
numbers
deviation = difference << mean #Apply second argument
35. Memoizing functions
• Memoizing Functions is a functional programming term for caching
the results of a function invocation.
• If a function always returns the same value when passed the same
arguments, if there is reason to believe that the same arguments
will be used repeatedly, and if the computation it performs is
somewhat expensive, then memoization may be a useful
optimization.
• We can automate memorization for Proc and Method objects with
the following method.
36. module Functional
# Return a new lambda that caches the results of this function and
# only calls the function when new arguments are supplied.
def memoize
cache = {} # An empty cache. The lambda captures this in its closure.
lambda {|*args|
# notice that the hash key is the entire array of arguments!
unless cache.has_key?(args) # If no cached result for these args
cache[args] = self[*args] # Compute and cache the result
end
cache[args] # Return result from cache
}
end
# A (probably unnecessary) unary + operator for memoization
# Mnemonic: the + operator means "improved"
alias +@ memoize # cached_f = +f
end
37. Contd..
• Here’s how we might use the memoize method or the unary + operator
# A memoized recursive factorial function
factorial = lambda {|x| return 1 if x==0; x*factorial[x-1];}.memoize
#Or, using the unary operator syntax
factorial = +lambda{|x| return 1 if x==0; x*factorial[x-1];}
• Here factorial is a recursive function, It calls the memoized version of
itself, which produces optimal caching.
factorial = lambda {|x| return 1 if x==0; x*factorial[x-1];}
cached_factorial = +factorial # Recursive calls are not cached!