In our third session we covered the second half of our language crash course. This session addresses Arrays, Hashes, Symbols, Control Structures, Regular Expressions, Blocks and Iterators.
Software Engineering Thailand: Programming with ScalaBrian Topping
Meet-up, May 28, 2015, Launchpad, Bangkok. http://www.meetup.com/Software-Engineering-Thailand/events/222548484/.
Apologies for the rendering quality not matching the presentation, I did these with Apple Keynote and Slideshare does not support this format. I will try to edit them when there is more time.
Thanks to Bangkok LaunchPad (https://www.facebook.com/launchpadhq) for generously hosting this event!
These are the slides from my RubyConf 2011 talk: "Keeping Ruby Reasonable". In this talk, I covered how first-class environments are implemented in Ruby, and why that poses a problem for Ruby programmers.
Elixir and Crystal are both descendants of the Ruby programming language, applying Ruby syntax and ideas to extremely different functional and OOP foundations. This talk compares all three languages and suggests appropriate cases for applying them.
In our third session we covered the second half of our language crash course. This session addresses Arrays, Hashes, Symbols, Control Structures, Regular Expressions, Blocks and Iterators.
Software Engineering Thailand: Programming with ScalaBrian Topping
Meet-up, May 28, 2015, Launchpad, Bangkok. http://www.meetup.com/Software-Engineering-Thailand/events/222548484/.
Apologies for the rendering quality not matching the presentation, I did these with Apple Keynote and Slideshare does not support this format. I will try to edit them when there is more time.
Thanks to Bangkok LaunchPad (https://www.facebook.com/launchpadhq) for generously hosting this event!
These are the slides from my RubyConf 2011 talk: "Keeping Ruby Reasonable". In this talk, I covered how first-class environments are implemented in Ruby, and why that poses a problem for Ruby programmers.
Elixir and Crystal are both descendants of the Ruby programming language, applying Ruby syntax and ideas to extremely different functional and OOP foundations. This talk compares all three languages and suggests appropriate cases for applying them.
Srihitha Technologies provides PHP Training in Ameerpet by real time Experts. For more information about PHP training in Ameerpet call 9394799566 / 9290641808.
When you're writing a Ruby on Rails application, certain decisions seem appropriate and good at the beginning, but come back to bite you later on. In this talk, I list 20 different "traps," things that seem appealing, but which you should think twice before doing. The talk is based on my experience teaching Ruby and Rails classes to many people over the years, and was a presentation at the "Rails Israel 2012" conference held in Tel Aviv.
We introduce Haskell. Why is it interesting. Where did it come from. What is it like. How to get started.
We show a GHCi session. We introduce simple recursive function and data. And we demo QuickCheck for testing properties of automatically generated data.
On my first session I would to introduce everyone to formerly known SQL Azure (actually Windows Azure SQL Database). Under Tips and Trick session I will show which points, features, compatibility and non-compatibility for SQL Azure are important for DBA's. I will cover functionalities, performance, cost, and sla and security aspects.
After break I will show how we can work with our data in the Cloud using SQL Azure, Blob Storage, what functionality of backup, restore, encryption and availability are available for us, how we can implement hybrid environment and when an why it is (or not) good practice.
And finally I hope we will find few minutes for discussion about Future of the DBA (not only in AD 2016)
Wysoka Dostępność SQL Server 2008 w kontekscie umów SLATobias Koprowski
To druga prezentacja w cztero-częściowym cyklu omawiającym znaczenie wysokiej dostepności w kontekście umów SLA. Prezentacje przeznaczone są dla odbiorców z kręgu ITPro, a publikowane na zywo na portalu VirtualStudy.pl
***
This is second part of my four-parts cycle about Service Level Agreement for ITPros. It a session for Virtualstudy.pl education portal.
Srihitha Technologies provides PHP Training in Ameerpet by real time Experts. For more information about PHP training in Ameerpet call 9394799566 / 9290641808.
When you're writing a Ruby on Rails application, certain decisions seem appropriate and good at the beginning, but come back to bite you later on. In this talk, I list 20 different "traps," things that seem appealing, but which you should think twice before doing. The talk is based on my experience teaching Ruby and Rails classes to many people over the years, and was a presentation at the "Rails Israel 2012" conference held in Tel Aviv.
We introduce Haskell. Why is it interesting. Where did it come from. What is it like. How to get started.
We show a GHCi session. We introduce simple recursive function and data. And we demo QuickCheck for testing properties of automatically generated data.
On my first session I would to introduce everyone to formerly known SQL Azure (actually Windows Azure SQL Database). Under Tips and Trick session I will show which points, features, compatibility and non-compatibility for SQL Azure are important for DBA's. I will cover functionalities, performance, cost, and sla and security aspects.
After break I will show how we can work with our data in the Cloud using SQL Azure, Blob Storage, what functionality of backup, restore, encryption and availability are available for us, how we can implement hybrid environment and when an why it is (or not) good practice.
And finally I hope we will find few minutes for discussion about Future of the DBA (not only in AD 2016)
Wysoka Dostępność SQL Server 2008 w kontekscie umów SLATobias Koprowski
To druga prezentacja w cztero-częściowym cyklu omawiającym znaczenie wysokiej dostepności w kontekście umów SLA. Prezentacje przeznaczone są dla odbiorców z kręgu ITPro, a publikowane na zywo na portalu VirtualStudy.pl
***
This is second part of my four-parts cycle about Service Level Agreement for ITPros. It a session for Virtualstudy.pl education portal.
A Whistleblowing Report to the United States of Congress submitted by Scott Bennett, 2LT, United States Army (Reserve), 11th Psychological Operations Battalion to the Department of Defense Inspector General, Memorial Day, May 27, 2013
The Betrayal and Cover-Up by the U.S. Government of the Union Bank of Switzerland - Terrorist Threat Financia Connection to Booz Allen Hamilton and U.S. Central Command
Scott Bennett - Shell Game (pdf source - http://projectcamelotportal.com/files/SHELL_GAME.pdf
• We sleeping well. And our mobile ringing and ringing. Message: DISASTER! In this session (on slides) we are NOT talk about potential disaster (such BCM); we talk about: And what NOW? New version old my old well-known session updated for whole changes which happened in DBA World in last two-three years.
• So, from the ground to the Sky and further - everything for surviving disaster. Which tasks should have been finished BEFORE. Is virtual or physical SQL matter? We talk about systems, databases, peoples, encryption, passwords, certificates and users.
• In this session (on few demos) I'll show which part of our SQL Server Environment are critical and how to be prepared to disaster. In some documents I'll show You how to be BEST prepared.
Introduction to SQL Server Analysis services 2008Tobias Koprowski
This is my presentation from 17th Polish SQL server User Group Meeting in Wroclaw. It\'s first part of Quadrology Bussiness Intelligence for ITPros Cycle.
Eventuosity For Event Producers and Service ProvidersJustin Panzer
Producing events is hard work. That's why your clients trust you to do the heavy lifting of everything from event strategy to project management. Do all of that in less time, at lower cost, and with greater control with eventuosity - the cloud-based, full-customizable collaboration platform for events.
Презентация стратегической игры MatriX UrbanАндрей Донских
Стратегическая игра MatriX Urban — это специализированная версия креативной платформы MatriX, предназначенная для поиска нестандартных и свежих решений по развитию территорий и моногородов, улучшению качества жизни населения, поиску новых форматов взаимодействия органов власти, бизнеса, экспертного сообщества, общественных организаций и других заинтересованных сторон.
MatriX Urban — это креативная платформа, предназначенная для проектирования будущего городов и проектов городского развития.
Активные городские сообщества и горожане понимают необходимость перемен и готовы брать на себя ответственность за настоящее и будущее своего города. Это проявляется в том, что они готовы созидательно участвовать в его среде.
Подробнее http://donskih.ru/matrix/matrix-urban/
Virtual Study Beta Exam 71-663 Exchange 2010 Designing And Deploying Messagin...Tobias Koprowski
This is my presentation for VirtualStudy.pl as teh last part of preparation for 71-663 beta exam: 71-663: Pro: Designing and Deploying Messaging Solutions with Microsoft Exchange Server 2010
Recent news about the pending shortage of data scientists prompts speculation about automation: will machines replace human analysts? We propose a model of automation, and briefly review progress in automated machine learning over the past twenty years. Summarizing the current state of the art, we look at some of the remaining challenges, and the implications for practicing data scientists.
Why is ERISA attorney Thomas Schendt so passionate about stopping retirement plan leakage? Because 401(k) loan defaults and a misunderstanding of plan sponsor requirements are costing plans billions every year. See why he believes this problem has a simple solution.
In our second session we began the first half of our language crash course. This session covered Classes vs. Objects, Duck Typing, Variables, Strings and Methods.
Mikhail Bortnyk, a senior developer at the Amoniac company, tells how to forget the pain of side effects and start to write your Erlang in Ruby.The presentation has been prepared for the Ruby Meditation conference #12.
Ruby Meditation 12 - 19.11.2016
His theme is Functional Ruby. How to forgot pain of side effects and start to write your Erlang in Ruby. Или просто очередная серебряная пуля для задач, которые вам никогда не попадутся.
#rubymeditation
A survey of all the hard problems JRuby developers have had to solve, whether the JVM likes it or not. Topics include parsing, interpreting, compiling, optimization, native libraries, posix, startup time, console features, and much more.
What can Ruby learn from Python (and vice versa)?Reuven Lerner
Ruby and Python are similar programming languages in many ways. But each has made different design decisions that affect how programmers in these languages think and work. In this talk, I contrast Ruby and Python, and some of the ways in which the languages differ.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
6. self.inspect
• Professionally writing software for 12
years
• Ruby for 3+ years
• Taught Ruby on Rails at RRC
• My biggest site has over 1 million
users
7. What is Ruby?
A dynamic, open source programming language
with a focus on simplicity and productivity.
It has an elegant syntax
that is natural to read and easy to write.
http://www.ruby-lang.org
9. What is Ruby?
“Ruby is simple in appearance,
but is very complex inside”
- Yukihiro Matsumoto
10. What is Ruby?
“Ruby is simple in appearance,
but is very complex inside”
“I wanted a scripting language that was more
powerful than Perl, and more object-oriented than
Python”
- Yukihiro Matsumoto
13. What is Ruby?
• Ruby is not Ruby on Rails
• Ruby is an interpreted language
14. What is Ruby?
• Ruby is not Ruby on Rails
• Ruby is an interpreted language
• script language
15. What is Ruby?
• Ruby is not Ruby on Rails
• Ruby is an interpreted language
• script language
• terse
16. What is Ruby?
• Ruby is not Ruby on Rails
• Ruby is an interpreted language
• script language
• terse
• completely Object Oriented
17. What is Ruby?
• Ruby is not Ruby on Rails
• Ruby is an interpreted language
• script language
• terse
• completely Object Oriented
• Free, really free.
30. What Can I do with
Ruby?
• Cross-platform GUI apps (WxRuby,
FXRuby, Ruby-GNOME2, Ruby Tk)
31. What Can I do with
Ruby?
• Cross-platform GUI apps (WxRuby,
FXRuby, Ruby-GNOME2, Ruby Tk)
• Mac Desktop apps with MacRuby and
Cocoa
32. What Can I do with
Ruby?
• Cross-platform GUI apps (WxRuby,
FXRuby, Ruby-GNOME2, Ruby Tk)
• Mac Desktop apps with MacRuby and
Cocoa
• Web Apps (Ruby on Rails, Sinatra)
33. What Can I do with
Ruby?
• Cross-platform GUI apps (WxRuby,
FXRuby, Ruby-GNOME2, Ruby Tk)
• Mac Desktop apps with MacRuby and
Cocoa
• Web Apps (Ruby on Rails, Sinatra)
• Replace Javascript?
34. What Can I do with
Ruby?
• Cross-platform GUI apps (WxRuby,
FXRuby, Ruby-GNOME2, Ruby Tk)
• Mac Desktop apps with MacRuby and
Cocoa
• Web Apps (Ruby on Rails, Sinatra)
• Replace Javascript?
• Soon Ruby.NET apps?
40. Differences from C++
• No type casting
• There’s only two container types:
Array and Hash
41. Differences from C++
• No type casting
• There’s only two container types:
Array and Hash
• There’s no type conversions, you’ll
probably find that they aren’t
necessary
42. Differences from C++
• No type casting
• There’s only two container types:
Array and Hash
• There’s no type conversions, you’ll
probably find that they aren’t
necessary
• Multithreading is built-in
45. Differences from C++
• A unit testing lib comes standard with
Ruby
• It’s self instead of this
46. Differences from C++
• A unit testing lib comes standard with
Ruby
• It’s self instead of this
• Objects are strongly but dynamically
typed. The runtime discovers at
runtime if that method call actually
works
49. Differences from Java
• There’s no static type checking.
• Variable names are just labels. They
don’t have a type associated with
them
50. Differences from Java
• There’s no static type checking.
• Variable names are just labels. They
don’t have a type associated with
them
• There are no type declarations
51. Differences from Java
• There’s no static type checking.
• Variable names are just labels. They
don’t have a type associated with
them
• There are no type declarations
• foo = Foo.new(“hi”) instead of
Foo foo = new Foo(“hi”)
52. Differences from Java
• There’s no static type checking.
• Variable names are just labels. They
don’t have a type associated with
them
• There are no type declarations
• foo = Foo.new(“hi”) instead of
Foo foo = new Foo(“hi”)
57. Variables
• Instance variables start with @
• Class variables start with @@
• Global variables start with $
• Any type of object can be stored in a
given variable
66. Symbols
• Symbols are similar to strings, but are
only allocated memory once, and are
never freed.
67. Symbols
• Symbols are similar to strings, but are
only allocated memory once, and are
never freed.
• Great for keys, column names, and
other strings that are repeated over
and over again.
80. Interpolation
• Double quoted strings are
interpolated, single quoted strings are
not.
puts “five times three is #{5 * 3}”
# five times three is 15
puts ‘five times three is #{5 * 3}’
# five times three is #{5 * 3}
157. Operators are Methods
• Most operators are methods
• and can be redefined
class Fixnum
def +(other)
self - other
end
end
158. Operators are Methods
• Most operators are methods
• and can be redefined
class Fixnum
def +(other)
self - other
end
end
5 + 3 # => 2
159. Blocks
• In Ruby, a block is a namless function
that can be stored as a callable object,
called a Proc
• Blocks can be stored in variables
• Blocks can be passed to methods to
customize their behavior
172. Block Objects are
Closures
• Block Objects (Procs) can be executed
anywhere and can take their context
(called binding) with them.
173. Block Objects are
Closures
• Block Objects (Procs) can be executed
anywhere and can take their context
(called binding) with them.
• A closure is a block of code that, when
run, is executed within the scope it
was defined (i.e. local variables are
available to the block), even after the
function has returned, and its local
scope has been destroyed.
217. class Car
def color
@color
end
def color=(color)
@color = color
end
...
218. class Car
def color
@color
class Car
end
def color=(color)
def color
@color = color
end
@color
def engine
@engine
end
def engine=(engine)
@engine = engine
end
end
def make
@make
end
def color=(color)
def make=(make)
@make = make
end @color = color
def model
@model
end
end
def model=(model)
@model = model
...
end
end
222. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
223. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
224. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
225. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
226. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
instance_variable_get("@#{attribute}")
227. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
instance_variable_get("@#{attribute}")
end
228. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
instance_variable_get("@#{attribute}")
end
# define setter
229. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
instance_variable_get("@#{attribute}")
end
# define setter
define_method("#{attribute}=") do |var|
230. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
instance_variable_get("@#{attribute}")
end
# define setter
define_method("#{attribute}=") do |var|
instance_variable_set("@#{attribute}", var)
231. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
instance_variable_get("@#{attribute}")
end
# define setter
define_method("#{attribute}=") do |var|
instance_variable_set("@#{attribute}", var)
end
232. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
instance_variable_get("@#{attribute}")
end
# define setter
define_method("#{attribute}=") do |var|
instance_variable_set("@#{attribute}", var)
end
}
233. class Car
attr_accessor :color, :engine, :make, :model
end
class Object
def self.attr_accessor(*attributes)
attributes.each{|attribute|
# define getter
define_method(attribute) do
instance_variable_get("@#{attribute}")
end
# define setter
define_method("#{attribute}=") do |var|
instance_variable_set("@#{attribute}", var)
end
}
end
248. Method Missing
• You can define ghost methods that
don’t actually exist, but pretend to
when requested
249. class Elephant
def initialize
@called = []
end
def method_missing(method, *args, &block)
@called << method
end
def talk
puts @called.inspect
end
end
250.
251. class Elephant
# ...
def method_missing(method, *args, &block)
@called << method
end
def talk # ...
end
252. class Elephant
# ...
def method_missing(method, *args, &block)
@called << method
end
def talk # ...
end
suzie = Elephant.new
253. class Elephant
# ...
def method_missing(method, *args, &block)
@called << method
end
def talk # ...
end
suzie = Elephant.new
suzie.brush
254. class Elephant
# ...
def method_missing(method, *args, &block)
@called << method
end
def talk # ...
end
suzie = Elephant.new
suzie.brush
suzie.do_tricks
255. class Elephant
# ...
def method_missing(method, *args, &block)
@called << method
end
def talk # ...
end
suzie = Elephant.new
suzie.brush
suzie.do_tricks
suzie.ride
256. class Elephant
# ...
def method_missing(method, *args, &block)
@called << method
end
def talk # ...
end
suzie = Elephant.new
suzie.brush
suzie.do_tricks
suzie.ride
suzie.talk # [‘brush’, ‘do_tricks’, ‘ride’]
258. class Html
def self.tag(tag_name, content)
"<#{tag_name}>#{content}</#{tag_name}>"
end
end
Html.tag(‘strong’, “I’m strong!”)
# <strong>I’m strong!</strong>
259. class Html
def self.tag(tag_name, content)
"<#{tag_name}>#{content}</#{tag_name}>"
end
def self.strong(content)
tag(‘strong’, content)
end
end
Html.strong(“I’m strong!”)
# <strong>I’m strong!</strong>
260. class Html
TAG_TYPES = [‘strong’, ‘div’, ‘span’, ‘a’, ‘ul’]
def self.tag(tag_name, content)
"<#{tag_name}>#{content}</#{tag_name}>"
end
def self.strong(content)
tag(‘strong’, content)
end
end
Html.strong(“I’m strong!”)
# <strong>I’m strong!</strong>
261. class Html
TAG_TYPES = %w(strong div span a ul)
def self.tag(tag_name, content)
"<#{tag_name}>#{content}</#{tag_name}>"
end
def self.strong(content)
tag(‘strong’, content)
end
end
Html.strong(“I’m strong!”)
# <strong>I’m strong!</strong>
262. class Html
TAG_TYPES = %w(strong div span a ul)
class << self
def tag(tag_name, content)
"<#{tag_name}>#{content}</
#{tag_name}>"
end
def strong(content)
tag(‘strong’, content)
end
end
end
263. class Html
TAG_TYPES = %w(strong div span a ul)
class << self
def tag(tag_name, content)
"<#{tag_name}>#{content}</#{tag_name}>"
end
TAG_TYPES.each{|tag_type|
define_method(tag_type) do |content|
tag(tag_type, content)
end
}
end
end
265. class Html
TAG_TYPES = %w(strong div span a ul)
class << self
def tag(tag_name, content)
"<#{tag_name}>#{content}</#{tag_name}>"
end
def method_missing(method, *args)
if TAG_TYPES.include?(method)
tag(method, *args)
else
super
end
end
end
end
266. class Html
class << self
def tag(tag_name, content)
"<#{tag_name}>#{content}</#{tag_name}>"
end
def method_missing(method, *args)
tag(method, *args)
end
end
end
289. module ActiveRecord
class RecordCannotBeDestroyed < ActiveRecordError
end
module Associations
module ClassMethods
def refuse_to_destroy!
module_eval %Q{
before_destroy do |record|
raise RecordCannotBeDestroyed, "You cannot destroy
#{record.class.name} records." unless record.new_record?
end
}
end
end
end
end
290. class User < ActiveRecord::Base
refuse_to_destroy!
end
# @user.destroy now raises an exception
291. def refuse_to_destroy!
module_eval %Q{
before_destroy do |record|
raise RecordCannotBeDestroyed, "You cannot destroy
#{record.class.name} records." unless record.new_record?
end
}
end
298. class Array
def include_with_regexp?(matcher)
if matcher.is_a?(Regexp)
any?{|i| i =~ matcher }
else
include_without_regexp?(matcher)
end
end
alias :include_without_regexp? :include?
alias :include? :include_with_regexp?
end
299. class Array
def include_with_regexp?(matcher)
if matcher.is_a?(Regexp)
any?{|i| i =~ matcher }
else
include_without_regexp?(matcher)
end
end
alias_method_chain :include?, :regexp
end
314. Object Proxy
class SpyProxy
def initialize(target)
@target = target
end
def method_missing(method, *args)
puts “#{method} called with args:
315. Object Proxy
class SpyProxy
def initialize(target)
@target = target
end
def method_missing(method, *args)
puts “#{method} called with args:
#{args.inspect}”
316. Object Proxy
class SpyProxy
def initialize(target)
@target = target
end
def method_missing(method, *args)
puts “#{method} called with args:
#{args.inspect}”
@target.send(method, *args)
317. Object Proxy
class SpyProxy
def initialize(target)
@target = target
end
def method_missing(method, *args)
puts “#{method} called with args:
#{args.inspect}”
@target.send(method, *args)
end
318. Object Proxy
class SpyProxy
def initialize(target)
@target = target
end
def method_missing(method, *args)
puts “#{method} called with args:
#{args.inspect}”
@target.send(method, *args)
end
end
323. Object Proxy
paul = Person.new
steve = Person. new
bmw = BMW. new
paul.start(bmw) # “clunk clunk”
324. Object Proxy
paul = Person.new
steve = Person. new
bmw = BMW. new
paul.start(bmw) # “clunk clunk”
steve.start(bmw) # “vroom vroom”
325. Object Proxy
paul = Person.new
steve = Person. new
bmw = BMW. new
paul.start(bmw) # “clunk clunk”
steve.start(bmw) # “vroom vroom”
spy_bmw = SpyProxy.new(bmw)
329. Object Proxy
spy_bmw = SpyProxy.new(bmw)
steve.start(spy_bmw)
# press_clutch called with args: [1.0]
330. Object Proxy
spy_bmw = SpyProxy.new(bmw)
steve.start(spy_bmw)
# press_clutch called with args: [1.0]
# turn_key called with args: []
331. Object Proxy
spy_bmw = SpyProxy.new(bmw)
steve.start(spy_bmw)
# press_clutch called with args: [1.0]
# turn_key called with args: []
# “vroom vroom”
332. Object Proxy
spy_bmw = SpyProxy.new(bmw)
steve.start(spy_bmw)
# press_clutch called with args: [1.0]
# turn_key called with args: []
# “vroom vroom”
paul.start(spy_bmw)
333. Object Proxy
spy_bmw = SpyProxy.new(bmw)
steve.start(spy_bmw)
# press_clutch called with args: [1.0]
# turn_key called with args: []
# “vroom vroom”
paul.start(spy_bmw)
# turn_key called with args: []
334. Object Proxy
spy_bmw = SpyProxy.new(bmw)
steve.start(spy_bmw)
# press_clutch called with args: [1.0]
# turn_key called with args: []
# “vroom vroom”
paul.start(spy_bmw)
# turn_key called with args: []
# “clunk clunk”
350. Self-Optimization
def get_random_user_id
class_eval {
user_count = sql("select count(*) from users")
define_method(‘get_random_user_id’) do
sql("select id from users
offset #{rand(user_count)} limit 1")
end
351. Self-Optimization
def get_random_user_id
class_eval {
user_count = sql("select count(*) from users")
define_method(‘get_random_user_id’) do
sql("select id from users
offset #{rand(user_count)} limit 1")
end
}
352. Self-Optimization
def get_random_user_id
class_eval {
user_count = sql("select count(*) from users")
define_method(‘get_random_user_id’) do
sql("select id from users
offset #{rand(user_count)} limit 1")
end
}
get_random_user_id
353. Self-Optimization
def get_random_user_id
class_eval {
user_count = sql("select count(*) from users")
define_method(‘get_random_user_id’) do
sql("select id from users
offset #{rand(user_count)} limit 1")
end
}
get_random_user_id
end
358. Caching by rewriting
methods?
• You can rewrite a method as a form of
caching
• Downside is cache invalidation
becomes messy (doable, think alias)
359. Caching by rewriting
methods?
• You can rewrite a method as a form of
caching
• Downside is cache invalidation
becomes messy (doable, think alias)
• There’s easier ways
360. Caching by rewriting
methods?
• You can rewrite a method as a form of
caching
• Downside is cache invalidation
becomes messy (doable, think alias)
• There’s easier ways
• @var ||= ...
361. Caching by rewriting
methods?
• You can rewrite a method as a form of
caching
• Downside is cache invalidation
becomes messy (doable, think alias)
• There’s easier ways
• @var ||= ...
• memoization (memoize in Rails)
362. Try Ruby in Your
Browser
http://TryRuby.org/
Download Ruby
http://www.ruby-lang.org/en/downloads/
2. Scripting language, but don&#x2019;t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
2. Scripting language, but don&#x2019;t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
2. Scripting language, but don&#x2019;t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
2. Scripting language, but don&#x2019;t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
2. Scripting language, but don&#x2019;t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
2. Scripting language, but don&#x2019;t call it php.4. smoothly elegant6. Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.
simplest thing that could possibly work
No libraries to import, no main declaration, no instantiation of string classes
This, is a thing of beauty.
Lets just get an idea of the syntax.
Notice I don&#x2019;t have to declare the type of the car variable, it&#x2019;s automatically assigned at runtime.
Lets just get an idea of the syntax.
Notice I don&#x2019;t have to declare the type of the car variable, it&#x2019;s automatically assigned at runtime.
Lets just get an idea of the syntax.
Notice I don&#x2019;t have to declare the type of the car variable, it&#x2019;s automatically assigned at runtime.
Lets just get an idea of the syntax.
Notice I don&#x2019;t have to declare the type of the car variable, it&#x2019;s automatically assigned at runtime.
Lets just get an idea of the syntax.
Notice I don&#x2019;t have to declare the type of the car variable, it&#x2019;s automatically assigned at runtime.
Lets just get an idea of the syntax.
Notice I don&#x2019;t have to declare the type of the car variable, it&#x2019;s automatically assigned at runtime.
Lets just get an idea of the syntax.
Notice I don&#x2019;t have to declare the type of the car variable, it&#x2019;s automatically assigned at runtime.
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
This is all fine and dandy, but does Ruby matter? I&#x2019;d argue that it&#x2019;s important.
If you can judge that by the number of Ruby implementations, then I&#x2019;d say so.
IronMonkey is Adobe VM
HotRuby is Ruby interpreter implemented in JS
IronRuby is Microsoft&#x2019;s work towards Ruby.NET
The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
The Silverlight Dynamic Languages SDK includes IronRuby, which allows you to write Ruby that runs in the browser
Here&#x2019;s an example of the GUI you can make with the WxRuby toolkit from Ruby
Here&#x2019;s the exact same library and code run on a Mac. Notice both are native to their own OS.
Let&#x2019;s get familiar with Ruby.
We&#x2019;re going to cover a lot of topics really quickly, so keep up. :)
important @
less important @@
global $, if you litter your code with these; your peers will surprise you at how creative they can be when it comes to hiding your lifeless body.
important @
less important @@
global $, if you litter your code with these; your peers will surprise you at how creative they can be when it comes to hiding your lifeless body.
important @
less important @@
global $, if you litter your code with these; your peers will surprise you at how creative they can be when it comes to hiding your lifeless body.
important @
less important @@
global $, if you litter your code with these; your peers will surprise you at how creative they can be when it comes to hiding your lifeless body.
local variables
This is what a symbol looks like. you can think of it as a string, and it is similar, but it&#x2019;s got a key difference which I&#x2019;ll get in to.
In Ruby, symbols are mostly used as hash keys, column names, for referencing data types, or used as contant values, but they are not just cheap strings.
This is what a symbol looks like. you can think of it as a string, and it is similar, but it&#x2019;s got a key difference which I&#x2019;ll get in to.
In Ruby, symbols are mostly used as hash keys, column names, for referencing data types, or used as contant values, but they are not just cheap strings.
This is what a symbol looks like. you can think of it as a string, and it is similar, but it&#x2019;s got a key difference which I&#x2019;ll get in to.
In Ruby, symbols are mostly used as hash keys, column names, for referencing data types, or used as contant values, but they are not just cheap strings.
This is what a symbol looks like. you can think of it as a string, and it is similar, but it&#x2019;s got a key difference which I&#x2019;ll get in to.
In Ruby, symbols are mostly used as hash keys, column names, for referencing data types, or used as contant values, but they are not just cheap strings.
The two name symbols here are literally the exact same object, where as the two name strings below are two separate objects that happen to have the same value.
The two name symbols here are literally the exact same object, where as the two name strings below are two separate objects that happen to have the same value.
The two name symbols here are literally the exact same object, where as the two name strings below are two separate objects that happen to have the same value.
The two name symbols here are literally the exact same object, where as the two name strings below are two separate objects that happen to have the same value.
curly braces represent a key-value hash, not a block of code ; the hash has keys and values
;; you can fetch the value for the keys
curly braces represent a key-value hash, not a block of code ; the hash has keys and values
;; you can fetch the value for the keys
curly braces represent a key-value hash, not a block of code ; the hash has keys and values
;; you can fetch the value for the keys
curly braces represent a key-value hash, not a block of code ; the hash has keys and values
;; you can fetch the value for the keys
curly braces represent a key-value hash, not a block of code ; the hash has keys and values
;; you can fetch the value for the keys
curly braces represent a key-value hash, not a block of code ; the hash has keys and values
;; you can fetch the value for the keys
{1}{2}, for example...
{1}{2}, for example...
means: you can change or extend any class. Good practices are up to you
OCP is ..
means: you can change or extend any class. Good practices are up to you
OCP is ..
means: you can change or extend any class. Good practices are up to you
OCP is ..
means: you can change or extend any class. Good practices are up to you
OCP is ..
lets reopen the Float class, and maybe our app doesn&#x2019;t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we&#x2019;ve done here. This violates the OCP
lets reopen the Float class, and maybe our app doesn&#x2019;t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we&#x2019;ve done here. This violates the OCP
lets reopen the Float class, and maybe our app doesn&#x2019;t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we&#x2019;ve done here. This violates the OCP
lets reopen the Float class, and maybe our app doesn&#x2019;t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we&#x2019;ve done here. This violates the OCP
lets reopen the Float class, and maybe our app doesn&#x2019;t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we&#x2019;ve done here. This violates the OCP
lets reopen the Float class, and maybe our app doesn&#x2019;t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we&#x2019;ve done here. This violates the OCP
lets reopen the Float class, and maybe our app doesn&#x2019;t want to round up ever. Our new CEO says rounding up is bad for business and we want to redefine round to call floor.
Now 5.7.round always returns 5. This is clearly a double-edged sword. You want to open classes for extension, not for modification as we&#x2019;ve done here. This violates the OCP
if we give the method a different name, it wont collide with the round function and break any existing code using it.
if we give the method a different name, it wont collide with the round function and break any existing code using it.
if we give the method a different name, it wont collide with the round function and break any existing code using it.
if we give the method a different name, it wont collide with the round function and break any existing code using it.
if we give the method a different name, it wont collide with the round function and break any existing code using it.
if we give the method a different name, it wont collide with the round function and break any existing code using it.
if we give the method a different name, it wont collide with the round function and break any existing code using it.
strings are objects.
integers are objects
integers are objects
integers are objects
integers are objects
integers are objects
integers are objects
integers are objects
integers are objects
floats are objects
floats are objects
floats are objects
shorthand
Arrays are objects. You can actually do some REALLY cool things with methods that array gives you by default, things you&#x2019;d normally write iterators and custom code for, but before we touch on that, I want to cover a little bit more background on Ruby
Like Array, You don&#x2019;t need to use Hash.new to create a new hash object in Ruby.
Using the braces is enough to denote that a hash object should be created
This shows a very common idiom in Ruby; using a hash to imitate Keyword Parameters
In fact, you don&#x2019;t even need to provide the braces, and Ruby still figures out that you are declaring a hash.
Regular Expressions are awesome. You should already be familiar with these as a programmer. If you&#x2019;re not, you&#x2019;re doing a lot of things the hard way. This is even more true in Ruby. Support for Regular expressions is built in, just like array and hash.
Once you have an expression, you can use it with the match operator
Once you have an expression, you can use it with the match operator
Once you have an expression, you can use it with the match operator
Handy with substitution
Handy with substitution
{1}, because of this, {2}, and {3}.
blocks with iteration
blocks with iteration
blocks with iteration
blocks with iteration
<=> is the comparison operator
<=> is the comparison operator
<=> is the comparison operator
<=> is the comparison operator
<=> is the comparison operator
A closure is a block of code that, when run, is executed within the scope it was defined (i.e. local variables are available to the block), even after the function has returned, and its local scope has been destroyed. the local variables remain in existence as part of the closure object. When nothing refers to the closure anymore, it's garbage collected, and the local variables go away.
A closure is a block of code that, when run, is executed within the scope it was defined (i.e. local variables are available to the block), even after the function has returned, and its local scope has been destroyed. the local variables remain in existence as part of the closure object. When nothing refers to the closure anymore, it's garbage collected, and the local variables go away.
Now that we know a little bit about blocks, lets go back to array and look at the map() method
map iterates the items in the array and calls the block you supply for each item, returning a new array with the results
Now that we know a little bit about blocks, lets go back to array and look at the map() method
map iterates the items in the array and calls the block you supply for each item, returning a new array with the results
inject is used for reduction. You reduce the items of an array down to a single value. in this example I&#x2019;m using it for summation
inject is used for reduction. You reduce the items of an array down to a single value. in this example I&#x2019;m using it for summation
inject is used for reduction. You reduce the items of an array down to a single value. in this example I&#x2019;m using it for summation
inject is used for reduction. You reduce the items of an array down to a single value. in this example I&#x2019;m using it for summation
we can use inject to easily add support for summation to the array class.
Now every array natively supports .sum. Rails gives you sum and .avg for free
we can use inject to easily add support for summation to the array class.
Now every array natively supports .sum. Rails gives you sum and .avg for free
we can use inject to easily add support for summation to the array class.
Now every array natively supports .sum. Rails gives you sum and .avg for free
we can use inject to easily add support for summation to the array class.
Now every array natively supports .sum. Rails gives you sum and .avg for free
we can use inject to easily add support for summation to the array class.
Now every array natively supports .sum. Rails gives you sum and .avg for free
we can use inject to easily add support for summation to the array class.
Now every array natively supports .sum. Rails gives you sum and .avg for free
we can use inject to easily add support for summation to the array class.
Now every array natively supports .sum. Rails gives you sum and .avg for free
Here I use inject to find the greatest number divisible by two in the array. inject keeps track of the best candidate, and I use a ternary operator to determine if i is a better candidate than my existing best.
Here I use inject to find the greatest number divisible by two in the array. inject keeps track of the best candidate, and I use a ternary operator to determine if i is a better candidate than my existing best.
Here I use inject to find the greatest number divisible by two in the array. inject keeps track of the best candidate, and I use a ternary operator to determine if i is a better candidate than my existing best.
Here I use inject to find the greatest number divisible by two in the array. inject keeps track of the best candidate, and I use a ternary operator to determine if i is a better candidate than my existing best.
I&#x2019;m sure all of you recognize the pattern of creating getters and setters for a class. I have a Car class here on the right with a getter and setter for a color attribute. On the left is the rest of the class with getters and setters for engine, make, and model. lot of repetition. Ruby embraces meta programming, and sets the bar for how we need to re-think what we might otherwise blindly accept as just &#x201C;the way our language works&#x201D;. In this case, the attr_accessor method.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
which shortens 33 lines of code down to three! But attr_accessor isn&#x2019;t magic Ruby compiler logic, it&#x2019;s just a method. We can take a look at what that method might look like. Don&#x2019;t worry if this goes over your head, I&#x2019;ll get in to each of the methods here after we see how they&#x2019;re used.
introspection
this gives you access to variables the class author might not have exposed.
Every object responds to instance_variables. Here we ask the Gem class from rubygems what instance variables it has defined internally. After it responds, we can query it for the value stored in any of those instance variables as if we had direct access to them.
every object responds to the .constants method. We can ask the Math module what constants it has defined. We can test them directly and see that they are in fact defined, and their values, but we can also request them by string, programatically. We can also set constants programmatically, as well as ask the class or module if they are defined, and even more weirdness with const_missing
inspect sums up my look at introspection. Every object in ruby responds to inspect with a string that describes the data the object holds, which, among other things, is handy for debugging
You&#x2019;ve already seen define_method, it&#x2019;s what made attr_accessor work.
but what happens when we want to implement div, span, anchors, unordered lists, etc?
First lets define a constant to hold all our tag types
There&#x2019;s a really handy syntax for writing arrays of strings with a single word each, it&#x2019;s %w()
before we go on, I&#x2019;m going to switch the syntax I&#x2019;m using to define class methods. instead of self.method_name I&#x2019;m using this class << self pattern which is going to help keep things clean.
now instead of defining the strong method ourselves, lets change that to iterate the TAG_TYPES array and define each method.
Now we have all these methods defined for free. If we later add support for list items, we don&#x2019;t have to add a method for it, we just add it to the TAG_TYPES array and the class automatically knows how to handle this.
Another way you can do this is with method_missing. Don&#x2019;t even define the methods, just respond when they&#x2019;re called.
In fact, why even have a list of supported tags at all? Now there&#x2019;s nothing to change to support new tags
You get really cool code. What does this remind you of? It&#x2019;s starting to look more and more like we created something that can generate XML for us. And in fact, that&#x2019;s exactly the premise behind the Builder gem package authored by Jim Weirich.
But there&#x2019;s a problem in using a class to generate xml that can use any tag name. Object already defines a ton of methods that if you try to call, will never hit method_missing, methods like new, id, send, freeze, class, and &#x201C;methods&#x201D;, and any class you define must descend from Object. Clearly, we need more magic.
But there&#x2019;s a problem in using a class to generate xml that can use any tag name. Object already defines a ton of methods that if you try to call, will never hit method_missing, methods like new, id, send, freeze, class, and &#x201C;methods&#x201D;, and any class you define must descend from Object. Clearly, we need more magic.
But there&#x2019;s a problem in using a class to generate xml that can use any tag name. Object already defines a ton of methods that if you try to call, will never hit method_missing, methods like new, id, send, freeze, class, and &#x201C;methods&#x201D;, and any class you define must descend from Object. Clearly, we need more magic.
Meet undef_method. Care to take a guess what this does?
Now, you might expect Html.methods to return an empty array now, *click*
buuut, we undefined it. *pause* So there&#x2019;s no more dot-methods method in our class.
Practically speaking, there&#x2019;s a couple methods you don&#x2019;t want to undefine, but lets just gloss over that.
With Builder you create a new builder object, in this example it&#x2019;s called &#x2018;xml&#x2019;. the methods you call on it become your tags. Blocks automatically nest tags within other tags.
And your output looks awesome. Life. is. good.
No, I&#x2019;m not talking about restricting instantiation of a class to a single object.
A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don&#x2019;t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don&#x2019;t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don&#x2019;t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don&#x2019;t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don&#x2019;t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don&#x2019;t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don&#x2019;t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
A common use for singleton methods would be for designing a GUI; A button is a button is a button, but you don&#x2019;t want each instance of a button to do the same thing. Singleton methods let us define or redefine instance methods on the fly for a single object.
eval - evaluates code, typically
class_eval - evaluates code in the context of the object&#x2019;s class, or metaclass
instance_eval - evals code in the context of the object,
module_eval - evals in context of a module
One day a specific client said to me, &#x201C;These records should never get destroyed, ever. I want something in place to prevent them from being destroyed&#x201D;. So, mixing the use of module_eval and the concept of creating a DSL, I came up with this patch. I reopen the ActiveRecord::Associations::ClassMethods module, which is part of Rails, and I define a class method called refuse_to_destroy!.
Now I have a DSL I can write in my models that tells it how to act. User.destroy now raises an exception
it works by evaluating the code in the User class and adds a before_destory hook on the ActiveRecord model.
I had this idiom in another language I came from, that essentially lets you temporarily change the scope. But when I came to Ruby, it just didn&#x2019;t exist.
But it turns out you can achieve something similar with instance_eval, since it changes the scope while the block executes. Cool, but it doesn&#x2019;t read as nice as that &#x201C;with&#x201D; command in my old language. But this is ruby, and you can make anything work the way you want it to!
We can add a with method to the Object class, which makes it available everywhere. We&#x2019;ll set it up to take an object and a block of code as parameters, then call instance_eval on the object to change the scope to that object, and pass the block along to instance_eval, which will execute it in the object&#x2019;s scope.
Now I have the syntax and method I was familiar with from the old language, implemented in Ruby. The great thing about this is there really is not a lot of limits on what you can do. You could almost create your own programming language or script, and execute it as if it&#x2019;s ruby code using instance_eval
There&#x2019;s already some really cool projects that take advantage of this. Cucumber actually executes english text as if it&#x2019;s code
really common in Ruby
railsy
almost all operators in ruby... are methods!
almost all operators in ruby... are methods!
almost all operators in ruby... are methods!
almost all operators in ruby... are methods!
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
My favorite kind of proxy is by far the spy proxy, though there are many uses for an object proxy (adding an optional layer of logic to a class, such as access control, for example, without modifying the class).
duck typing, looks like a duck, quacks like a duck, we don&#x2019;t care.
ppl objects are interacting with our bmw differently
duck typing, looks like a duck, quacks like a duck, we don&#x2019;t care.
ppl objects are interacting with our bmw differently
duck typing, looks like a duck, quacks like a duck, we don&#x2019;t care.
ppl objects are interacting with our bmw differently
duck typing, looks like a duck, quacks like a duck, we don&#x2019;t care.
ppl objects are interacting with our bmw differently
duck typing, looks like a duck, quacks like a duck, we don&#x2019;t care.
ppl objects are interacting with our bmw differently
duck typing, looks like a duck, quacks like a duck, we don&#x2019;t care.
ppl objects are interacting with our bmw differently
duck typing, looks like a duck, quacks like a duck, we don&#x2019;t care.
ppl objects are interacting with our bmw differently
duck typing, looks like a duck, quacks like a duck, we don&#x2019;t care.
ppl objects are interacting with our bmw differently
lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn&#x2019;t really that fast either, but lets call it negligible.
lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn&#x2019;t really that fast either, but lets call it negligible.
lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn&#x2019;t really that fast either, but lets call it negligible.
lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn&#x2019;t really that fast either, but lets call it negligible.
lets say we have a method that does two things. the first it does very very slowly (perhaps, reading through 10 million database records to get the record count)
the second it does much faster (finding a specific record). Now, in my experience with mysql, offset isn&#x2019;t really that fast either, but lets call it negligible.
There are other ways to solve this problem, like making user count an instance variable and using the &#x201C;or equals&#x201D; meme (meam) you see here, which only evaluates the code on the right and sets user count if user count is nil or false. But lets ignore that, too.
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
class_eval lets us evaluate the block of code as if we were running it inside the class, and not the current method. define_method takes a block, which it turns in to a closure--meaning it keeps a reference to the local variable user_count, so it doesn&#x2019;t drop out of scope and get freed
after the first time the method runs, it redefines itself to something like this. The method has both rewritten itself and accomplished a form of caching at the same time.
self-optimization-code similar to this is used by Rails internally for routing. The first time the method is called it generates its own routing methods based on a more complete picture of what&#x2019;s required and cuts out a lot of dead cycles that would otherwise check routes that are never used.
If you&#x2019;re liking the Ruby vibe and you want to get in to it a little more, you&#x2019;ll want to make a note to visit some of these sites.