This is the same talk, except with all my speaker notes. I use speaker notes post-talk as a way to explain and "tutorialize" a presentation, so enjoy!
The presentation I did at Fog City Ruby over how === works and some of the things you can do with it.
Want more? Try these articles where I explain some of it:
* https://medium.com/@baweaver/for-want-of-pattern-matching-in-ruby-the-creation-of-qo-c3b267109b25
* https://medium.com/@baweaver/for-want-of-pattern-matching-in-ruby-the-creation-of-qo-c3b267109b25
Ruby makes it easy to create domain specific languages (DSLs) in two main ways:
1) Internal DSLs extend and customize the syntax and semantics of Ruby to achieve domain-specific needs, while external DSLs define their own custom syntax that requires a parser.
2) Techniques like method parameters, blocks, instance evaluation, method missing, and core extensions allow Ruby code to take on the feel of a specialized language within a domain.
3) Popular Ruby frameworks like Rails contain many internal DSLs that customize Ruby for tasks like defining routes, models, and more using these techniques.
An introduction to Perl and what you can learn in an introductory course. An entire "eliza"-like program is written and the perl features explained in about twenty minutes.
This document appears to be a series of slides from a lightning talk presentation comparing Go and Ruby programming languages. It discusses various differences between the two languages such as Go having static and strict typing while Ruby has dynamic and flexible typing. It also covers topics like memory layout, methods, inheritance between classes, and embedding types in Go. Code examples are provided to illustrate concepts in both languages.
Slides from talk given at Ithaca Web Group and GORGES on CoffeeScript.
The focus is on explaining to people who haven't tried it yet that it's more than syntactic sugar. There are several real life code examples but they were explained verbally so they may not be super helpful if you don't know CoffeeScript yet.
It's an overview, not a tutorial.
A spreadsheet error in a 2010 research paper by Carmen Reinhart and Kenneth Rogoff undermined their conclusion that high debt-to-GDP ratios correlate with lower economic growth. Specifically, the paper incorrectly excluded several countries with debt over 90% GDP from its analysis, weakening the claimed relationship between high debt and slow growth that was influential in policymaking. The error was revealed in 2013 through independent research, demonstrating how easily mistakes can propagate in spreadsheets and the importance of transparent data and methodology.
Ruby provides various ways to define and manipulate methods. Methods can be defined on classes, objects, and singleton classes. Singleton classes allow defining methods that are only available to a specific object. Ruby also supports currying methods to return procs that can later be called. Methods can be aliased, undefined, or dynamically defined/manipulated at runtime using techniques like eval, instance_eval, and reflection. Classes in Ruby are also objects that can have singleton classes and methods defined on them.
This document provides an overview of types in Go compared to Ruby. Some key points:
- Go uses static, struct-based types while Ruby uses dynamic, class-based types.
- In Go, types are defined with the type keyword and methods are defined on specific types. In Ruby, classes define types and inheritance.
- Go types are static and checked at compile-time. Ruby types are dynamic and can change at runtime.
- Go uses interfaces to define common method sets. Ruby uses mixins and inheritance for polymorphism.
The document provides examples of defining types and methods in Go, and uses classes and inheritance in Ruby. It discusses how Go prioritizes static types while Ruby
This document provides an introduction and overview of the Ruby programming language. It discusses installing Ruby on Windows and Linux/OSX systems, running Ruby scripts, using the interactive Ruby shell (IRB), creating and running .rb files. It also covers key Ruby concepts like classes and objects, duck typing, attributes and accessors, arrays, hashes, symbols, blocks and iterators.
Ruby makes it easy to create domain specific languages (DSLs) in two main ways:
1) Internal DSLs extend and customize the syntax and semantics of Ruby to achieve domain-specific needs, while external DSLs define their own custom syntax that requires a parser.
2) Techniques like method parameters, blocks, instance evaluation, method missing, and core extensions allow Ruby code to take on the feel of a specialized language within a domain.
3) Popular Ruby frameworks like Rails contain many internal DSLs that customize Ruby for tasks like defining routes, models, and more using these techniques.
An introduction to Perl and what you can learn in an introductory course. An entire "eliza"-like program is written and the perl features explained in about twenty minutes.
This document appears to be a series of slides from a lightning talk presentation comparing Go and Ruby programming languages. It discusses various differences between the two languages such as Go having static and strict typing while Ruby has dynamic and flexible typing. It also covers topics like memory layout, methods, inheritance between classes, and embedding types in Go. Code examples are provided to illustrate concepts in both languages.
Slides from talk given at Ithaca Web Group and GORGES on CoffeeScript.
The focus is on explaining to people who haven't tried it yet that it's more than syntactic sugar. There are several real life code examples but they were explained verbally so they may not be super helpful if you don't know CoffeeScript yet.
It's an overview, not a tutorial.
A spreadsheet error in a 2010 research paper by Carmen Reinhart and Kenneth Rogoff undermined their conclusion that high debt-to-GDP ratios correlate with lower economic growth. Specifically, the paper incorrectly excluded several countries with debt over 90% GDP from its analysis, weakening the claimed relationship between high debt and slow growth that was influential in policymaking. The error was revealed in 2013 through independent research, demonstrating how easily mistakes can propagate in spreadsheets and the importance of transparent data and methodology.
Ruby provides various ways to define and manipulate methods. Methods can be defined on classes, objects, and singleton classes. Singleton classes allow defining methods that are only available to a specific object. Ruby also supports currying methods to return procs that can later be called. Methods can be aliased, undefined, or dynamically defined/manipulated at runtime using techniques like eval, instance_eval, and reflection. Classes in Ruby are also objects that can have singleton classes and methods defined on them.
This document provides an overview of types in Go compared to Ruby. Some key points:
- Go uses static, struct-based types while Ruby uses dynamic, class-based types.
- In Go, types are defined with the type keyword and methods are defined on specific types. In Ruby, classes define types and inheritance.
- Go types are static and checked at compile-time. Ruby types are dynamic and can change at runtime.
- Go uses interfaces to define common method sets. Ruby uses mixins and inheritance for polymorphism.
The document provides examples of defining types and methods in Go, and uses classes and inheritance in Ruby. It discusses how Go prioritizes static types while Ruby
This document provides an introduction and overview of the Ruby programming language. It discusses installing Ruby on Windows and Linux/OSX systems, running Ruby scripts, using the interactive Ruby shell (IRB), creating and running .rb files. It also covers key Ruby concepts like classes and objects, duck typing, attributes and accessors, arrays, hashes, symbols, blocks and iterators.
The document discusses various string manipulation functions in PHP including:
1. Functions to search and extract parts of strings like strpos(), substr(), strstr().
2. Functions to decompose strings like explode(), strtok(), sscanf().
3. Functions to manipulate strings like str_replace(), strrev(), str_pad().
It provides examples of how to use each function, the required parameters, and sample code. The document also covers decomposing URLs using parse_url() and tokenizing strings.
The document provides information about new features and integration of Symfony and Doctrine. It discusses updates to the DoctrineBundle and new bundles for MongoDB integration and database migrations. It also covers using the Doctrine database abstraction layer independently and the object relational mapper, including entity management, querying, and schema management.
This document discusses strings in Python. It shows how to create strings, concatenate strings using the + operator, use print() to output strings, and run Python scripts. It also covers string slicing to access parts of a string, string indices, the len() function, and calculating string halfway points using integer division.
Rapid Development with Ruby/JRuby and Railselliando dias
This document discusses Ruby and Rails development. It provides an overview of Ruby as a scripting language created by Yukihiro Matsumoto in 1993 with a focus on readability. Key aspects of Ruby covered include conventions, classes, symbols, closures, duck typing, and metaprogramming. The document also discusses how JRuby allows Java developers to use Ruby on the JVM and benefit from Ruby tools like Rails.
Presented at 8th Light University London (13th May 2016)
Do this, do that. Coding from assembler to shell scripting, from the mainstream languages of the last century to the mainstream languages now, is dominated by an imperative style. From how we teach variables — they vary, right? — to how we talk about databases, we are constantly looking at state as a thing to be changed and programming languages are structured in terms of the mechanics of change — assignment, loops and how code can be threaded (cautiously) with concurrency.
Functional programming, mark-up languages, schemas, persistent data structures and more are all based around a more declarative approach to code, where instead of reasoning in terms of who does what to whom and what the consequences are, relationships and uses are described, and the flow of execution follows from how functions, data and other structures are composed. This talk will look at the differences between imperative and declarative approaches, offering lessons, habits and techniques that are applicable from requirements through to code and tests in mainstream languages.
This document discusses Ruby on Rails extensions provided by ActiveSupport. It explains that ActiveSupport provides Ruby extensions, utility classes, and other features used across Rails. It then summarizes some common extensions, including methods added to all objects like blank?, present?, and try. The document provides code examples for how these extensions work and which ActiveSupport files define them.
This document discusses tuples in Python. It begins with definitions of tuples, noting that they are ordered, indexed and immutable sequences. It then provides examples of creating tuples using parentheses or not, and explains that a single element tuple requires a trailing comma. The document discusses tuple operations like slicing, comparison, assignment and using tuples as function return values or dictionary keys. It also covers built-in tuple methods and functions.
You’ve built a WordPress site or two (or 10), your installed plugins and themes to MOSTLY get what you want. Now you’re ready to learn the inner workings of WordPress and take your development to the next level. Jump into WordPress development and PHP by building a Plugin and learn to speak WordPress’ language: PHP.
The document discusses functions in R, including function structure, calling conventions, writing functions, and using for loops. It provides examples of basic function structure, including name, arguments, body, and output. It also discusses passing arguments by name or position and using default values. The document demonstrates how to write functions to calculate mean and variance and provides exercises for readers to write functions and use for loops to iterate through data frames.
The document discusses aliasing in Python programming. It explains that an alias is a second name for a piece of data. It provides examples of how aliasing can cause bugs when working with mutable data like lists, but not with immutable data. It also discusses why Python allows aliasing despite the potential for bugs - for efficiency when working with large data structures and because sometimes in-place updates are desired.
This document discusses several common JavaScript design patterns including Singleton, Factory, Module, Decorator, Command, and Observer patterns. It provides descriptions and code examples for each pattern. The Singleton pattern ensures a class only has one instance and provides a global access point. Factory patterns are used for object creation. The Module pattern provides private and public encapsulation for classes. The Decorator pattern attaches additional responsibilities to objects dynamically. The Command pattern encapsulates requests as objects, and the Observer pattern allows objects to watch other objects for changes.
Twig is a template engine for PHP. It parses templates into tags, prints, and blocks. The lexer tokenizes templates into tokens, and the parser converts tokens into an AST. The compiler generates PHP code from the AST. Twig supports tags like for loops and if/else, macros, and internationalization. It can be extended with custom tags, filters, functions. Security features include escaping, sandboxing and permissions. Templates can access objects and be rendered without controllers.
Kotlin is a statically typed language that runs on the JVM, Android and browsers. It was developed by JetBrains and had its first stable release in February 2016. Some key features of Kotlin include null safety, lambdas, extension functions, and delegation which allow avoiding null checks and reducing boilerplate code compared to Java. It also integrates well with Android by reducing the need for findViewById and providing libraries like Anko that simplify common tasks. Performance tests have shown Kotlin to be as fast as Java.
Python quickstart for programmers: Python Kung Fuclimatewarrior
The document provides an overview of key Python concepts including data types, operators, control flow statements, functions, objects and classes. It discusses lists in depth, covering creation, iteration, searching and common list methods. It also briefly touches on modules, exceptions, inheritance and other advanced topics.
This document provides an overview of the Ruby programming language. It discusses Ruby's clean and meaningful syntax, everything being an object, dynamic typing and duck typing, open classes, blocks, mixins, testing, standard library, and gems. Ruby aims to be productive and fun to use.
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesTchelinux
Sobre o palestrante: Formado na UFPel no início do ano corrente, trabalhou com desenvolvimento de hardware para TV digital durante a graduação. Entretanto, sempre foi apaixonado por belas linguagens de programação, e destas, Ruby é a que mais se destaca. Atualmente aguarda o mês de junho, quando começa a trabalhar na ThoughtWorks, em Porto Alegre.
This document provides an overview of mocks and stubs in testing, using Ruby and RSpec examples. It establishes common terminology around mock objects, shows appropriate uses of mocks such as defining interfaces and simulating situations, and demonstrates abuses such as modifying the subject under test and creating "mock trainwrecks" that tie specs too tightly to implementation details. The goal is to understand best practices for using mocks to write clear, maintainable tests.
Michael Schwern presents Method::Signatures, a module that allows defining Perl subroutines with function signatures in a syntax inspired by Perl 6. It works by rewriting the code at compile time using Devel::Declare rather than a source filter. Key features demonstrated include required and optional parameters, named and positional arguments, aliases, and more. While powerful, the module is still a work in progress, with debugging support and better error handling needing further work. The goal is to implement a "signatures" pragma for inclusion in Perl 5.
Making JavaScript Libraries More ApproachablePamela Fox
A talk given at NotConf in Phoenix, Texas in 2012.
(Alternative title: Why nested ternary operators make me want to kick inanimate objects in the nuts.)
Ruby is a dynamic, open source object-oriented scripting language that is interpreted, not compiled. It supports features like garbage collection, exception handling, operator overloading, and just-in-time compilation. Ruby can be used for web development, system scripting, database programming, and GUI development. It uses classes and modules to support object-oriented programming concepts like inheritance, polymorphism, and mixins.
The document discusses various string manipulation functions in PHP including:
1. Functions to search and extract parts of strings like strpos(), substr(), strstr().
2. Functions to decompose strings like explode(), strtok(), sscanf().
3. Functions to manipulate strings like str_replace(), strrev(), str_pad().
It provides examples of how to use each function, the required parameters, and sample code. The document also covers decomposing URLs using parse_url() and tokenizing strings.
The document provides information about new features and integration of Symfony and Doctrine. It discusses updates to the DoctrineBundle and new bundles for MongoDB integration and database migrations. It also covers using the Doctrine database abstraction layer independently and the object relational mapper, including entity management, querying, and schema management.
This document discusses strings in Python. It shows how to create strings, concatenate strings using the + operator, use print() to output strings, and run Python scripts. It also covers string slicing to access parts of a string, string indices, the len() function, and calculating string halfway points using integer division.
Rapid Development with Ruby/JRuby and Railselliando dias
This document discusses Ruby and Rails development. It provides an overview of Ruby as a scripting language created by Yukihiro Matsumoto in 1993 with a focus on readability. Key aspects of Ruby covered include conventions, classes, symbols, closures, duck typing, and metaprogramming. The document also discusses how JRuby allows Java developers to use Ruby on the JVM and benefit from Ruby tools like Rails.
Presented at 8th Light University London (13th May 2016)
Do this, do that. Coding from assembler to shell scripting, from the mainstream languages of the last century to the mainstream languages now, is dominated by an imperative style. From how we teach variables — they vary, right? — to how we talk about databases, we are constantly looking at state as a thing to be changed and programming languages are structured in terms of the mechanics of change — assignment, loops and how code can be threaded (cautiously) with concurrency.
Functional programming, mark-up languages, schemas, persistent data structures and more are all based around a more declarative approach to code, where instead of reasoning in terms of who does what to whom and what the consequences are, relationships and uses are described, and the flow of execution follows from how functions, data and other structures are composed. This talk will look at the differences between imperative and declarative approaches, offering lessons, habits and techniques that are applicable from requirements through to code and tests in mainstream languages.
This document discusses Ruby on Rails extensions provided by ActiveSupport. It explains that ActiveSupport provides Ruby extensions, utility classes, and other features used across Rails. It then summarizes some common extensions, including methods added to all objects like blank?, present?, and try. The document provides code examples for how these extensions work and which ActiveSupport files define them.
This document discusses tuples in Python. It begins with definitions of tuples, noting that they are ordered, indexed and immutable sequences. It then provides examples of creating tuples using parentheses or not, and explains that a single element tuple requires a trailing comma. The document discusses tuple operations like slicing, comparison, assignment and using tuples as function return values or dictionary keys. It also covers built-in tuple methods and functions.
You’ve built a WordPress site or two (or 10), your installed plugins and themes to MOSTLY get what you want. Now you’re ready to learn the inner workings of WordPress and take your development to the next level. Jump into WordPress development and PHP by building a Plugin and learn to speak WordPress’ language: PHP.
The document discusses functions in R, including function structure, calling conventions, writing functions, and using for loops. It provides examples of basic function structure, including name, arguments, body, and output. It also discusses passing arguments by name or position and using default values. The document demonstrates how to write functions to calculate mean and variance and provides exercises for readers to write functions and use for loops to iterate through data frames.
The document discusses aliasing in Python programming. It explains that an alias is a second name for a piece of data. It provides examples of how aliasing can cause bugs when working with mutable data like lists, but not with immutable data. It also discusses why Python allows aliasing despite the potential for bugs - for efficiency when working with large data structures and because sometimes in-place updates are desired.
This document discusses several common JavaScript design patterns including Singleton, Factory, Module, Decorator, Command, and Observer patterns. It provides descriptions and code examples for each pattern. The Singleton pattern ensures a class only has one instance and provides a global access point. Factory patterns are used for object creation. The Module pattern provides private and public encapsulation for classes. The Decorator pattern attaches additional responsibilities to objects dynamically. The Command pattern encapsulates requests as objects, and the Observer pattern allows objects to watch other objects for changes.
Twig is a template engine for PHP. It parses templates into tags, prints, and blocks. The lexer tokenizes templates into tokens, and the parser converts tokens into an AST. The compiler generates PHP code from the AST. Twig supports tags like for loops and if/else, macros, and internationalization. It can be extended with custom tags, filters, functions. Security features include escaping, sandboxing and permissions. Templates can access objects and be rendered without controllers.
Kotlin is a statically typed language that runs on the JVM, Android and browsers. It was developed by JetBrains and had its first stable release in February 2016. Some key features of Kotlin include null safety, lambdas, extension functions, and delegation which allow avoiding null checks and reducing boilerplate code compared to Java. It also integrates well with Android by reducing the need for findViewById and providing libraries like Anko that simplify common tasks. Performance tests have shown Kotlin to be as fast as Java.
Python quickstart for programmers: Python Kung Fuclimatewarrior
The document provides an overview of key Python concepts including data types, operators, control flow statements, functions, objects and classes. It discusses lists in depth, covering creation, iteration, searching and common list methods. It also briefly touches on modules, exceptions, inheritance and other advanced topics.
This document provides an overview of the Ruby programming language. It discusses Ruby's clean and meaningful syntax, everything being an object, dynamic typing and duck typing, open classes, blocks, mixins, testing, standard library, and gems. Ruby aims to be productive and fun to use.
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesTchelinux
Sobre o palestrante: Formado na UFPel no início do ano corrente, trabalhou com desenvolvimento de hardware para TV digital durante a graduação. Entretanto, sempre foi apaixonado por belas linguagens de programação, e destas, Ruby é a que mais se destaca. Atualmente aguarda o mês de junho, quando começa a trabalhar na ThoughtWorks, em Porto Alegre.
This document provides an overview of mocks and stubs in testing, using Ruby and RSpec examples. It establishes common terminology around mock objects, shows appropriate uses of mocks such as defining interfaces and simulating situations, and demonstrates abuses such as modifying the subject under test and creating "mock trainwrecks" that tie specs too tightly to implementation details. The goal is to understand best practices for using mocks to write clear, maintainable tests.
Michael Schwern presents Method::Signatures, a module that allows defining Perl subroutines with function signatures in a syntax inspired by Perl 6. It works by rewriting the code at compile time using Devel::Declare rather than a source filter. Key features demonstrated include required and optional parameters, named and positional arguments, aliases, and more. While powerful, the module is still a work in progress, with debugging support and better error handling needing further work. The goal is to implement a "signatures" pragma for inclusion in Perl 5.
Making JavaScript Libraries More ApproachablePamela Fox
A talk given at NotConf in Phoenix, Texas in 2012.
(Alternative title: Why nested ternary operators make me want to kick inanimate objects in the nuts.)
Ruby is a dynamic, open source object-oriented scripting language that is interpreted, not compiled. It supports features like garbage collection, exception handling, operator overloading, and just-in-time compilation. Ruby can be used for web development, system scripting, database programming, and GUI development. It uses classes and modules to support object-oriented programming concepts like inheritance, polymorphism, and mixins.
- Test-First Teaching involves writing tests before writing code to make the tests pass one by one. This helps students learn incrementally and receive immediate feedback.
- It encourages writing small, focused tests and code to address one problem at a time. Students learn by seeing their code pass each test.
- Research has found Test-First Teaching effective for learning programming languages like Ruby based on various studies and examples developed by independent instructors over time.
The document discusses Ruby's === operator and how it can be used to emulate pattern matching. It explains how === is used internally by classes like Integer, Regexp, and Range to check object equality. It then shows how to write custom matcher classes and procedures to select objects based on multiple criteria, like selecting people objects that match a name regex and fall within an age range. Finally, it provides examples of pattern matching libraries like Qo that build on these concepts.
This document provides an introduction to jRuby, which allows Ruby code to be run on the Java Virtual Machine. It discusses the history and creator of Ruby, Yukihiro "Matz" Matsumoto, and his goals for the language. It then provides a primer on Ruby syntax including booleans, strings, numbers, arrays, hashes, symbols, and classes. It demonstrates how Ruby code can interact with Java code when using jRuby, such as calling Java classes and methods from Ruby. It also discusses metaprogramming in Ruby and how jRuby enables cross-platform GUI development using Java libraries.
This presentation covers various "gotchas" or unexpected behaviors in Ruby that can trip up programmers. It begins with simple gotchas like string interpolation requiring double quotes and progresses to more advanced gotchas. Some of the gotchas discussed include: the difference between symbols and strings, truthy vs falsey values, constant reassignment only issuing a warning, class variable sharing between subclasses, block variable scoping, freezing arrays freezing contents but not elements, bang methods not always returning the expected value, and exceptions using raise/rescue rather than throw/catch. The presentation encourages watching out for these gotchas and referring back to it if Ruby behaves unexpectedly. It offers to add additional gotchas people encounter.
Ruby is an object-oriented scripting language that is dynamically typed and supports duck typing. It was created in the 1990s by Yukihiro "Matz" Matsumoto and has gained popularity through its use in web frameworks like Ruby on Rails. This document provides an overview of the Ruby language, including its history, basic syntax like strings and methods, core data types, control structures, classes and inheritance. It also discusses tools used by Ruby developers like RubyGems, interactive Ruby shells, and practical applications of Ruby for web development, testing, and automation through scripting. Finally, it mentions the international Ruby community and local user groups.
Fancy is a JavaScript library that combines Underscore functions with functional programming concepts to allow for writing functional code in a more readable way. It constructs FancyArrays and FancyObjects from normal arrays and objects that allow chaining of Underscore functions. This functional approach to problems like evaluating poker hands avoids side effects, combines functions, and solves problems conceptually rather than using loops. While it may not implement all aspects of functional programming, Fancy emphasizes the use of functions and avoids state to make code more reusable, abstracted, and easier to write and extend.
This document provides an overview of functional programming concepts in Ruby. It discusses the history and advantages of functional programming, comparing the functional and object-oriented paradigms. It introduces functional programming concepts like pure functions, recursion, immutable data, and higher-order functions. It demonstrates how these concepts can be applied in Ruby using functions, closures, currying, composition, and the Enumerable module. Overall, the document serves as a high-level introduction to thinking functionally in Ruby.
Spring Expression Language (SpEL) provides a powerful and concise syntax for wiring beans and accessing data in Spring. It can be used to configure beans in XML or with annotations. SpEL supports common operators and functions, accessing objects and properties, collection selection and projection, and more advanced features like custom functions and security enhancements. While SpEL adds flexibility, it has a performance cost compared to using plain Java code due to the overhead of parsing expressions.
- The document discusses testing Ruby code with RSpec, including setting up RSpec, the four phases of testing (setup, exercise, verify, teardown), describe and it blocks, matchers, stubs, mocks, focus and skip, shared examples, shared contexts, and custom matchers.
- Key aspects covered include initializing RSpec with bundle, writing tests with describe/it blocks, using matchers like expect() to verify results, and techniques like stubs, mocks, focus/skip, and shared examples/contexts.
- The document provides examples of testing methods, using matchers, stubs, focus/skip, and shared examples/contexts.
I am Alex N. I am a Python Homework Expert at pythonhomeworkhelp.com. I hold a Master's in Python Programming from, Leeds Trinity University. I have been helping students with their homework for the past 10 years. I solve homework related to Python.
Visit pythonhomeworkhelp.com or email support@pythonhomeworkhelp.com.
You can also call on +1 678 648 4277 for any assistance with Python Homework.
CPAP.com Introduction to Coding: Part 1johnnygoodman
This document provides an introduction to coding concepts. It discusses storing values in variables and data types like strings and integers. Key coding concepts covered include comments, running code, comparisons, arrays, and if/else statements. The document outlines what future sessions will cover, including loops, classes, methods, connecting to databases, and using other people's code.
Ruby on Rails is a popular web application framework written in Ruby. It follows the model-view-controller (MVC) pattern and includes components like Action Pack, Active Support, Active Record, and Action Mailer. The document provides an overview of Rails, Ruby basics, installing Rails, the directory structure of a Rails application, and the MVC pattern.
Similar to Fog City Ruby - Triple Equals Black Magic with speaker notes (20)
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving
What began over 115 years ago as a supplier of precision gauges to the automotive industry has evolved into being an industry leader in the manufacture of product branding, automotive cockpit trim and decorative appliance trim. Value-added services include in-house Design, Engineering, Program Management, Test Lab and Tool Shops.
Discover the Unseen: Tailored Recommendation of Unwatched ContentScyllaDB
The session shares how JioCinema approaches ""watch discounting."" This capability ensures that if a user watched a certain amount of a show/movie, the platform no longer recommends that particular content to the user. Flawless operation of this feature promotes the discover of new content, improving the overall user experience.
JioCinema is an Indian over-the-top media streaming service owned by Viacom18.
"NATO Hackathon Winner: AI-Powered Drug Search", Taras KlobaFwdays
This is a session that details how PostgreSQL's features and Azure AI Services can be effectively used to significantly enhance the search functionality in any application.
In this session, we'll share insights on how we used PostgreSQL to facilitate precise searches across multiple fields in our mobile application. The techniques include using LIKE and ILIKE operators and integrating a trigram-based search to handle potential misspellings, thereby increasing the search accuracy.
We'll also discuss how the azure_ai extension on PostgreSQL databases in Azure and Azure AI Services were utilized to create vectors from user input, a feature beneficial when users wish to find specific items based on text prompts. While our application's case study involves a drug search, the techniques and principles shared in this session can be adapted to improve search functionality in a wide range of applications. Join us to learn how PostgreSQL and Azure AI can be harnessed to enhance your application's search capability.
In our second session, we shall learn all about the main features and fundamentals of UiPath Studio that enable us to use the building blocks for any automation project.
📕 Detailed agenda:
Variables and Datatypes
Workflow Layouts
Arguments
Control Flows and Loops
Conditional Statements
💻 Extra training through UiPath Academy:
Variables, Constants, and Arguments in Studio
Control Flow in Studio
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...Jason Yip
The typical problem in product engineering is not bad strategy, so much as “no strategy”. This leads to confusion, lack of motivation, and incoherent action. The next time you look for a strategy and find an empty space, instead of waiting for it to be filled, I will show you how to fill it in yourself. If you’re wrong, it forces a correction. If you’re right, it helps create focus. I’ll share how I’ve approached this in the past, both what works and lessons for what didn’t work so well.
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Ukraine
Під час доповіді відповімо на питання, навіщо потрібно підвищувати продуктивність аплікації і які є найефективніші способи для цього. А також поговоримо про те, що таке кеш, які його види бувають та, основне — як знайти performance bottleneck?
Відео та деталі заходу: https://bit.ly/45tILxj
Dandelion Hashtable: beyond billion requests per second on a commodity serverAntonios Katsarakis
This slide deck presents DLHT, a concurrent in-memory hashtable. Despite efforts to optimize hashtables, that go as far as sacrificing core functionality, state-of-the-art designs still incur multiple memory accesses per request and block request processing in three cases. First, most hashtables block while waiting for data to be retrieved from memory. Second, open-addressing designs, which represent the current state-of-the-art, either cannot free index slots on deletes or must block all requests to do so. Third, index resizes block every request until all objects are copied to the new index. Defying folklore wisdom, DLHT forgoes open-addressing and adopts a fully-featured and memory-aware closed-addressing design based on bounded cache-line-chaining. This design offers lock-free index operations and deletes that free slots instantly, (2) completes most requests with a single memory access, (3) utilizes software prefetching to hide memory latencies, and (4) employs a novel non-blocking and parallel resizing. In a commodity server and a memory-resident workload, DLHT surpasses 1.6B requests per second and provides 3.5x (12x) the throughput of the state-of-the-art closed-addressing (open-addressing) resizable hashtable on Gets (Deletes).
ScyllaDB is making a major architecture shift. We’re moving from vNode replication to tablets – fragments of tables that are distributed independently, enabling dynamic data distribution and extreme elasticity. In this keynote, ScyllaDB co-founder and CTO Avi Kivity explains the reason for this shift, provides a look at the implementation and roadmap, and shares how this shift benefits ScyllaDB users.
Must Know Postgres Extension for DBA and Developer during MigrationMydbops
Mydbops Opensource Database Meetup 16
Topic: Must-Know PostgreSQL Extensions for Developers and DBAs During Migration
Speaker: Deepak Mahto, Founder of DataCloudGaze Consulting
Date & Time: 8th June | 10 AM - 1 PM IST
Venue: Bangalore International Centre, Bangalore
Abstract: Discover how PostgreSQL extensions can be your secret weapon! This talk explores how key extensions enhance database capabilities and streamline the migration process for users moving from other relational databases like Oracle.
Key Takeaways:
* Learn about crucial extensions like oracle_fdw, pgtt, and pg_audit that ease migration complexities.
* Gain valuable strategies for implementing these extensions in PostgreSQL to achieve license freedom.
* Discover how these key extensions can empower both developers and DBAs during the migration process.
* Don't miss this chance to gain practical knowledge from an industry expert and stay updated on the latest open-source database trends.
Mydbops Managed Services specializes in taking the pain out of database management while optimizing performance. Since 2015, we have been providing top-notch support and assistance for the top three open-source databases: MySQL, MongoDB, and PostgreSQL.
Our team offers a wide range of services, including assistance, support, consulting, 24/7 operations, and expertise in all relevant technologies. We help organizations improve their database's performance, scalability, efficiency, and availability.
Contact us: info@mydbops.com
Visit: https://www.mydbops.com/
Follow us on LinkedIn: https://in.linkedin.com/company/mydbops
For more details and updates, please follow up the below links.
Meetup Page : https://www.meetup.com/mydbops-databa...
Twitter: https://twitter.com/mydbopsofficial
Blogs: https://www.mydbops.com/blog/
Facebook(Meta): https://www.facebook.com/mydbops/
What is an RPA CoE? Session 1 – CoE VisionDianaGray10
In the first session, we will review the organization's vision and how this has an impact on the COE Structure.
Topics covered:
• The role of a steering committee
• How do the organization’s priorities determine CoE Structure?
Speaker:
Chris Bolin, Senior Intelligent Automation Architect Anika Systems
From Natural Language to Structured Solr Queries using LLMsSease
This talk draws on experimentation to enable AI applications with Solr. One important use case is to use AI for better accessibility and discoverability of the data: while User eXperience techniques, lexical search improvements, and data harmonization can take organizations to a good level of accessibility, a structural (or “cognitive” gap) remains between the data user needs and the data producer constraints.
That is where AI – and most importantly, Natural Language Processing and Large Language Model techniques – could make a difference. This natural language, conversational engine could facilitate access and usage of the data leveraging the semantics of any data source.
The objective of the presentation is to propose a technical approach and a way forward to achieve this goal.
The key concept is to enable users to express their search queries in natural language, which the LLM then enriches, interprets, and translates into structured queries based on the Solr index’s metadata.
This approach leverages the LLM’s ability to understand the nuances of natural language and the structure of documents within Apache Solr.
The LLM acts as an intermediary agent, offering a transparent experience to users automatically and potentially uncovering relevant documents that conventional search methods might overlook. The presentation will include the results of this experimental work, lessons learned, best practices, and the scope of future work that should improve the approach and make it production-ready.
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsDianaGray10
Join us to learn how UiPath Apps can directly and easily interact with prebuilt connectors via Integration Service--including Salesforce, ServiceNow, Open GenAI, and more.
The best part is you can achieve this without building a custom workflow! Say goodbye to the hassle of using separate automations to call APIs. By seamlessly integrating within App Studio, you can now easily streamline your workflow, while gaining direct access to our Connector Catalog of popular applications.
We’ll discuss and demo the benefits of UiPath Apps and connectors including:
Creating a compelling user experience for any software, without the limitations of APIs.
Accelerating the app creation process, saving time and effort
Enjoying high-performance CRUD (create, read, update, delete) operations, for
seamless data management.
Speakers:
Russell Alfeche, Technology Leader, RPA at qBotic and UiPath MVP
Charlie Greenberg, host
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor IvaniukFwdays
At this talk we will discuss DDoS protection tools and best practices, discuss network architectures and what AWS has to offer. Also, we will look into one of the largest DDoS attacks on Ukrainian infrastructure that happened in February 2022. We'll see, what techniques helped to keep the web resources available for Ukrainians and how AWS improved DDoS protection for all customers based on Ukraine experience
QA or the Highway - Component Testing: Bridging the gap between frontend appl...zjhamm304
These are the slides for the presentation, "Component Testing: Bridging the gap between frontend applications" that was presented at QA or the Highway 2024 in Columbus, OH by Zachary Hamm.
The Microsoft 365 Migration Tutorial For Beginner.pptxoperationspcvita
This presentation will help you understand the power of Microsoft 365. However, we have mentioned every productivity app included in Office 365. Additionally, we have suggested the migration situation related to Office 365 and how we can help you.
You can also read: https://www.systoolsgroup.com/updates/office-365-tenant-to-tenant-migration-step-by-step-complete-guide/
In the realm of cybersecurity, offensive security practices act as a critical shield. By simulating real-world attacks in a controlled environment, these techniques expose vulnerabilities before malicious actors can exploit them. This proactive approach allows manufacturers to identify and fix weaknesses, significantly enhancing system security.
This presentation delves into the development of a system designed to mimic Galileo's Open Service signal using software-defined radio (SDR) technology. We'll begin with a foundational overview of both Global Navigation Satellite Systems (GNSS) and the intricacies of digital signal processing.
The presentation culminates in a live demonstration. We'll showcase the manipulation of Galileo's Open Service pilot signal, simulating an attack on various software and hardware systems. This practical demonstration serves to highlight the potential consequences of unaddressed vulnerabilities, emphasizing the importance of offensive security practices in safeguarding critical infrastructure.
"Scaling RAG Applications to serve millions of users", Kevin GoedeckeFwdays
How we managed to grow and scale a RAG application from zero to thousands of users in 7 months. Lessons from technical challenges around managing high load for LLMs, RAGs and Vector databases.
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fog City Ruby - Triple Equals Black Magic with speaker notes
1. === BLACK MAGIC
@KEYSTONELEMUR
Hey! Welcome to the speaker notes. For the most part I tend to use these as an expanded version of what I’m talking about so you, the reader, have more context about
what I’m talking about. That includes links, references, and a bit more detailed explanations than what I may have time for in the presentation.
That said, enjoy! It’ll be a fun ride.
3. WHO AM I?
My name is Brandon Weaver
I work at Square
I love Ruby, Javascript, and Lemurs
@keystonelemur
The Lemur part is a bit clearer with the fun fact that gets mentioned before I give this talk. Working on writing an intro book to Ruby using Lemurs to teach, it’s a great
time. Ah, side tracking.
5. HOW === WORKS
===
@keystonelemur
Well, if you’re coming from Javascript you’re in for a bit of a surprise, because it’s most certainly not a stricter equality operator. If anything, it’s substantially looser which
has earned it the name case equality or matching equality operator.
6. HOW === WORKS
/^f/ === 'foo'
@keystonelemur
You can use it explicitly, though most Rubyists would really prefer you don’t. Match is way clearer here and should be used as such. There are reasons to use ===
explicitly, sure, but easy on the magic syntax in app level code.
7. HOW === WORKS
def ===(v)
@keystonelemur
Really, like any of the operators, it’s just a method. That means it can be overridden, and it also means that if you get === backwards it’s not going to work like you think
it will like ==. It’s left-biased, so keep that in mind before you explicitly use it. I still mix them up, truth be told, so I cheat and wrap it in a method :D
9. HOW === WORKS
class Integer
def ===(v)
self == v
end
end
@keystonelemur
Integer and most classes are boring, they just use it as an alias of ==. You can call === off of it but it won’t make a lick of difference.
10. HOW === WORKS
class Regexp
def ===(v)
match? v
end
end
@keystonelemur
Now regex? That’s a different story. Some classes redefine it to be somewhat of a set inclusion. For something to === a regex it’d have to “match” it, hence `match?`
being used there like that.
11. HOW === WORKS
Regexp = match?
Range = include?
Class = is_a?
Proc = call
@keystonelemur
Here are a few examples of classes that do interesting things to it. Noted that Proc is an odd bird. Most return exclusively boolean results, Proc just calls things. I’d
complain more about that not making much sense, but I like to leverage that to make Ruby do interesting things.
It’s not exhaustive, you should check into this article if you want that:
https://medium.com/rubyinside/triple-equals-black-magic-d934936a6379
I go into a lot more detail there. Really, it’s a good read overall after this talk.
12. HOW === WORKS
/^f/ === 'foo'
(1..10) === 1
String === 's'
-> a {a+1} === 2
@keystonelemur
Here’s a few examples of explicit calls. Again, Proc is an odd bird. That’s the same as `Proc#call` which means you get back 3. This is very useful, but definitely starts to
go the path of darker magics in Ruby. Ramda is a particularly interesting way to use that, see the article I linked to in the last slide notes.
13. WHERE’S ===
HIDING?
@keystonelemur
So if it’s so bad to use explicitly, why do we have it? Well turns out it gets used behind the scenes in more than a few things, which allows some very expressive code if
you know what it’s doing.
14. WHERE’S === HIDING?
case value
when String
'string'
when Integer
0
end
@keystonelemur
Every single branch of a case statement will use ===. That means you can pseudo-static type things if you’re really interested in that, though I wouldn’t suggest it for
dispatch as it can get slow.
Apparently the Stripe folks made a C++ static type library they’re demoing at RubyKaigi, but I don’t have links for that one yet.
15. WHERE’S === HIDING?
[1, 2, 3.0].grep(Integer)
# => [1, 2]
@keystonelemur
Grep will compare everything with === as well. Think of it as select, but with ===. grep_v is the inverse, primarily because command line flags like `-v` invert grep kinda
like select/reject.
16. WHERE’S === HIDING?
[1, 2, 3.0].all?(Integer)
# => false
@keystonelemur
In 2.5 all the predicate methods started responding to === type arguments as well. That means any, all, none, and one.
17. WHAT’S A
CLOSURE?
@keystonelemur
Before we get into later segments of this, be warned, a lot of black magic is coming and it might be a bit dense for beginners. I’ll do my best to make it digestible, but feel
free to ping me for questions later if it doesn’t make sense.
18. WHAT’S A CLOSURE?
adder = proc { |a|
proc { |b| a + b }
}
add3 = adder.call(3)
[1,2,3].map(&add3)
# => [4,5,6]
@keystonelemur
A closure is a function which remembers the context around where it was created. In this case we have a function, adder, which takes an argument ‘a’.
19. WHAT’S A CLOSURE?
adder = proc { |a|
proc { |b| a + b }
}
add3 = adder.call(3)
[1,2,3].map(&add3)
# => [4,5,6]
@keystonelemur
It returns a proc which takes an argument ‘b’. The interesting bit about closures here is that that function that got returned remembers what ‘a’ was when it was created.
20. WHAT’S A CLOSURE?
adder = proc { |a|
proc { |b| a + b }
}
add3 = adder.call(3)
[1,2,3].map(&add3)
# => [4,5,6]
@keystonelemur
So if we called it with 3, we now have a function returned waiting for one more argument that’ll add 3 to it.
21. WHAT’S A CLOSURE?
adder = proc { |a|
proc { |b| a + b }
}
add3 = adder.call(3)
[1,2,3].map(&add3)
# => [4,5,6]
@keystonelemur
Then we just pass it to something like map and it adds 3 to everything!
22. WHAT’S A CLOSURE?
adder = proc { |a|
proc { |b| a + b }
}
[1,2,3].map(&adder.call(3))
# => [4,5,6]
@keystonelemur
Though you could totally inline it as well. As long as map gets a function it’s perfectly happy to apply it to everything in that list.
23. EMULATING
PATTERN MATCHING
@keystonelemur
Got most of that? If not this article might help some: https://medium.com/@baweaver/reducing-enumerable-the-basics-fa042ce6806
It’s going to get a lot more dense from here, into some advanced territory. If it gets confusing, feel free to ping me and I’ll work on explaining it a bit better. I may even
write an article explaining some of the basics of Functional Programming later that covers this, so keep an eye on Medium for a few of those over the next few weeks.
24. EMULATING PATTERN MATCHING
query = proc { |*matchers|
proc { |target|
matchers.all? { |m| m === target }
}
}
[1,1.0,'s'].select(&query.call(
Integer, 1..10, :odd?.to_proc
))
# => [1]
@keystonelemur
Remembering what we know of closures, we can make a function which takes a number of arguments. Remember, a proc, like a method, can take multiple types of
arguments like varadic (star) or keyword (double star, hash args).
25. EMULATING PATTERN MATCHING
query = proc { |*matchers|
proc { |target|
matchers.all? { |m| m === target }
}
}
[1,1.0,'s'].select(&query.call(
Integer, 1..10, :odd?.to_proc
))
# => [1]
@keystonelemur
So it returns a function waiting for a target to “match” against, remembering what the matchers were when it was created.
26. EMULATING PATTERN MATCHING
query = proc { |*matchers|
proc { |target|
matchers.all? { |m| m === target }
}
}
[1,1.0,'s'].select(&query.call(
Integer, 1..10, :odd?.to_proc
))
# => [1]
@keystonelemur
Given those matchers, we check if all of them match the target. Notice, and this is important, that the matcher is on the LEFT side of the equation. If all the matchers we
pass “match” the target, we get back true.
We can’t use the === trick from 2.5 because we’re checking `all?` against a list of === respondent entities.
27. EMULATING PATTERN MATCHING
query = proc { |*matchers|
proc { |target|
matchers.all? { |m| m === target }
}
}
[1,1.0,'s'].select(&query.call(
Integer, 1..10, :odd?.to_proc
))
# => [1]
@keystonelemur
So we take a list of 1, 1.0, and the string ’s’ and we use our query with select. Our matchers are Integer, 1..10, and :odd? as a proc. That means we only want to select
values that match all three of those.
Notice I didn’t use &:odd? here. You can only do that once in a to_proc coercion, otherwise Ruby gets confused. I’ve run afoul of this one a few times.
28. EMULATING PATTERN MATCHING
query = proc { |*matchers|
proc { |target|
matchers.all? { |m| m === target }
}
}
[1,1.0,'s'].select(&query.call(
Integer, 1..10, :odd?.to_proc
))
# => [1]
@keystonelemur
1 is an Integer between 1 and 10 that happens to be odd, so only it passes.
29. EMULATING PATTERN MATCHING
people = [
{name: 'Foo', age: 42},
{name: 'Bar', age: 20},
{name: 'Baz', age: 30},
{name: 'Boo', age: 10},
]
@keystonelemur
So let’s say instead of just an array, we have an array of hashes to match against. Remember keyword arguments? They get to be real fun around here.
30. EMULATING PATTERN MATCHING
query = proc { |**matchers|
proc { |target|
matchers.all? { |k,m|
m === target[k]
}
}
}
people.select(&query.call(
name: /^Foo/, age: 40..50
))
# => [{name: 'Foo', age: 42}]
@keystonelemur
So instead of using *matchers, we use **matchers. That means we can pass keyword arguments instead. The problem with this is that you can only use Symbols here
which makes for a real pain when you have String keys of things. You can’t pass string keys as keyword arguments either.
There are ways around this by coercing things and double-checking values, but it becomes a huge performance hit after a while so keep that in mind. Hash with
indifferent access is even worse on performance, so another bit to keep in mind.
31. EMULATING PATTERN MATCHING
query = proc { |**matchers|
proc { |target|
matchers.all? { |k,m|
m === target[k]
}
}
}
people.select(&query.call(
name: /^Foo/, age: 40..50
))
# => [{name: 'Foo', age: 42}]
@keystonelemur
Anyways, ranting over, we again return a function awaiting a target
32. EMULATING PATTERN MATCHING
query = proc { |**matchers|
proc { |target|
matchers.all? { |k,m|
m === target[k]
}
}
}
people.select(&query.call(
name: /^Foo/, age: 40..50
))
# => [{name: 'Foo', age: 42}]
@keystonelemur
And instead of === against the target directly, we get the value of the target at the key provided, so we end up with name comparing ‘Foo’ to the regex /^Foo/ and so on.
33. EMULATING PATTERN MATCHING
query = proc { |**matchers|
proc { |target|
matchers.all? { |k,m|
m === target[k]
}
}
}
people.select(&query.call(
name: /^Foo/, age: 40..50
))
# => [{name: 'Foo', age: 42}]
@keystonelemur
So like the previous match, we can pass our “matchers” in and it’ll give us back values which “match” it.
34. EMULATING PATTERN MATCHING
query = proc { |**matchers|
proc { |target|
matchers.all? { |k,m|
m === target[k]
}
}
}
people.select(&query.call(
name: /^Foo/, age: 40..50
))
# => [{name: 'Foo', age: 42}]
@keystonelemur
In this case, only Foo matches.
35. EMULATING PATTERN MATCHING
people_objects = people.map { |v|
OpenStruct.new(v)
}
@keystonelemur
Though let’s say we have a collection of Objects instead. OpenStruct is a cheap way to make something that looks like a Person object with properties for name and age.
36. EMULATING PATTERN MATCHING
query = proc { |**matchers|
proc { |target|
matchers.all? { |k,m|
m === target.public_send(k)
}
}
}
people_objects.select(&query.call(
name: /^Foo/, age: 40..50
))
# => [OS(name: 'Foo', age: 42)]
@keystonelemur
The only difference between this and out Hash matcher is we use public_send instead of a key accessor. That means we can match against method calls as well, but we
want to use public_send to keep people from doing anything too particularly mischievous with it.
(Ok ok ok, fine, OpenStruct responds to both but that’s not the point of this slide)
37. EMULATING PATTERN MATCHING
query = proc { |**matchers|
proc { |target|
matchers.all? { |k,m|
m === target.public_send(k)
}
}
}
people_objects.select(&query.call(
name: /^Foo/, age: 40..50
))
# => [OS(name: 'Foo', age: 42)]
@keystonelemur
So amusingly the syntax is exactly the same on the outside, we just get back OpenStruct “people” instead!
38. CLASS
WRAPPERS
@keystonelemur
But really, you don’t need closures to pull this off, they just make for a bit of a quicker implementation. Know what else encapsulates state and lets you pass around
context? A class!
39. CLASS WRAPPERS
class Query
def initialize(*ms) @ms = ms end
def to_proc
proc { |v| self.call(v) }
end
def call(v)
@ms.all? { |m| m === v }
end
alias_method :===, :call
end
@keystonelemur
We’ll just assume veridic matchers for now. There are ways to take both and fork the query depending on which it got and what type of target it gets, but that’s an
exercise for the watcher / reader. ( ps - reading Qo’s source is cheating :P )
We just want to remember what the matchers are in this case. I use ms because slides are a bit small and I’d prefer to make the font larger for the people in the back.
40. CLASS WRAPPERS
class Query
def initialize(*ms) @ms = ms end
def to_proc
proc { |v| self.call(v) }
end
def call(v)
@ms.all? { |m| m === v }
end
alias_method :===, :call
end
@keystonelemur
Any time you see &something in Ruby, it’s saying call `to_proc` on whatever is after it. Notice that &:odd? syntax? That’s Symbol#to_proc. This is Query#to_proc.
We’re awaiting a target, v, and sending it to “call”
41. CLASS WRAPPERS
class Query
def initialize(*ms) @ms = ms end
def to_proc
proc { |v| self.call(v) }
end
def call(v)
@ms.all? { |m| m === v }
end
alias_method :===, :call
end
@keystonelemur
Call looks very familiar to our previous match logic. It remembers the matchers, and can run them all against a target value.
We can also alias it to === and [] to make it behave more like a proc if we want to.
42. CLASS WRAPPERS
class Query
def initialize(*ms) @ms = ms end
def to_proc
proc { |v| self.call(v) }
end
def call(v)
@ms.all? { |m| m === v }
end
alias_method :===, :call
end
@keystonelemur
That leaves us with a class that does about the same thing as the previous closure in a bit more of a Ruby-Oriented way. Why show you closures then? Because they
come in real handy whenever you start getting deeper into some of this stuff, and it’s a good tool to have on your belt.
44. CLASS WRAPPERS
case 1
when Query.new(Integer, 1..10)
# …
else
end
@keystonelemur
Remember that === alias? Case does. Now you can use queries pretty freely here.
45. IN THE WILD
@keystonelemur
Now how does this look when we apply it to the wild wild west of Rubyland? Well, turns out a lot of fun and the subject of a lot of the more advanced articles I’ve been
putting out recently. === is actually one of the foundational pieces to creating a pattern matching library in Ruby.
46. IN THE WILD - QO (PATTERN MATCHING)
people.map(&Qo.match { |m|
m.when(age: 13..19) { |person|
"#{person.name} is a teen"
}
m.else { |person|
"#{person.name} is #{person.age} years old"
}
})
people.select(&Qo.and(age: 10..19, name: /^F/))
@keystonelemur
Qo is what happens when I spend way too long with Scala and reading TC39 proposals after listening to Pat talk about pattern matching in Haskell. It started a few
months ago as a thought experiment, and now it exists.
The problem with a case statement is you can’t really do much with the value after you get it. It also doesn’t stack nicely with passing directly to map. With techniques
like you saw here, we can use a “query” as a guard statement for blocks of code to execute in sequence.
47. IN THE WILD - QO (PATTERN MATCHING)
people.map(&Qo.match { |m|
m.when(age: 13..19) { |person|
"#{person.name} is a teen"
}
m.else { |person|
"#{person.name} is #{person.age} years old”
}
})
people.select(&Qo.and(age: 10..19, name: /^F/))
@keystonelemur
Query objects tend to be used a bit more often though
48. IN THE WILD - SF (BLACK MAGIC)
(1..100).map(&Qo.match { |m|
m.when(Sf % 15 == 0) { 'FizzBuzz' }
m.when(Sf % 5 == 0) { 'Fizz' }
m.when(Sf % 3 == 0) { 'Buzz' }
m.else { |n| n }
})
@keystonelemur
Now I promised you black magic, so here’s the worst of it. Infix operators can be redefined, and Qo uses === for all matchers, meaning we can stack them to get
something that looks a lot like a Scala expression. Sf is super super black magic hackery, and should likely never see the light of production. That said, it was still really
really dang fun to make.