housekeeping - association for computing machinery · 2018-02-01 · • long-time rubyconf...
Post on 01-Aug-2020
1 Views
Preview:
TRANSCRIPT
“Housekeeping”
• Welcome to today’s ACM Webinar. The presentation starts at the top of the hour.
• If you are experiencing any problems/issues, refresh your console by pressing the F5 key on your keyboard in Windows, Command + R if on a Mac, or refresh your browser if you’re on a mobile device; or close and re-launch the presentation. You can also view the Webcast Help Guide, by clicking on the “Help” widget in the bottom dock.
• To control volume, adjust the master volume on your computer.
• If you think of a question during the presentation, please type it into the Q&A box and click on the submit button. You do not need to wait until the end of the presentation to begin submitting questions.
• At the end of the presentation, you’ll see a survey URL on the final slide. Please take a minute to click on the link and fill it out to help us improve your next webinar experience.
• You can download a copy of these slides by clicking on the Resources widget in the bottom dock.
• This presentation is being recorded and will be available for on-demand viewing in the next 1-2 days. You will receive an automatic e-mail notification when the recording is ready.
1
Ruby for the Nuby
ACM Learning Webinar
David A. Black Lead Developer
Cyrus Innovation
March 27, 2014
• 1,400+ trusted technical books and videos by leading publishers including O’Reilly, Morgan Kaufmann, others
• Online courses with assessments and certification-track mentoring, member discounts on tuition at partner institutions
• Learning Webinars on big topics (Cloud/Mobile Development, Cybersecurity, Big Data, Recommender Systems, SaaS, Agile, Machine Learning, Natural Language Processing, Parallel Programming, etc.)
• ACM Tech Packs on top current computing topics: Annotated Bibliographies compiled by subject experts
• Popular video tutorials/keynotes from ACM Digital Library, A.M. Turing Centenary talks/panels
• Podcasts with industry leaders/award winners
ACM Learning Center http://learning.acm.org
3
“Housekeeping”
• Welcome to today’s ACM Webinar. The presentation starts at the top of the hour.
• If you are experiencing any problems/issues, refresh your console by pressing the F5 key on your keyboard in Windows, Command + R if on a Mac, or refresh your browser if you’re on a mobile device; or close and re-launch the presentation. You can also view the Webcast Help Guide, by clicking on the “Help” widget in the bottom dock.
• To control volume, adjust the master volume on your computer.
• If you think of a question during the presentation, please type it into the Q&A box and click on the submit button. You do not need to wait until the end of the presentation to begin submitting questions.
• At the end of the presentation, you’ll see a survey URL on the final slide. Please take a minute to click on the link and fill it out to help us improve your next webinar experience.
• You can download a copy of these slides by clicking on the Resources widget in the bottom dock.
• This presentation is being recorded and will be available for on-demand viewing in the next 1-2 days. You will receive an automatic e-mail notification when the recording is ready.
4
Talk Back
• Use the Facebook widget in the bottom panel to share this presentation with friends and colleagues
• Use Twitter widget to Tweet your favorite quotes from today’s presentation with hashtag #ACMWebinarRuby
• Submit questions and comments via Twitter to @acmeducation – we’re reading them!
About me
• Lead developer at Cyrus Innovation • Rubyist since 2000 • Author of The Well-Grounded Rubyist (Manning 2009;
second edition forthcoming 2014) • Founding former director of Ruby Central • Long-time RubyConf organizer • Ruby/Ruby on Rails trainer • Ruby standard library contributor (chief author of scanf.rb)
About Ruby
• Created and still guided by Yukihiro "matz" Matsumoto • First announced in February 1993 • Version 1.0 12/25/1996 • Object-oriented • Ancestors include Smalltalk, LISP, Perl, CLU • Very dynamic • Untyped variables • Introduced widely outside Japan via Programming Ruby
(Pragmatic Programmers, 2000) • Further popularized by Ruby on Rails (2004)
Some basic basics
puts "Hello, world!"
x = 10
y = x * 2
def greet
puts "Hello, world!"
end
def shout
puts "Hello, world!".upcase
end
greet => Hello, world!
shout => HELLO, WORLD!
Some basic basics, cont'd
a = 1
b = 2
if a > b
puts "Huh?"
else
puts "That's more like it."
end
=> That's more like it.
REPL with irb
• Command-line interactive Ruby interpreter • Ships with Ruby
$ irb --simple-prompt
>> a = 1
=> 1
>> b = 2
=> 2
>> a + b
=> 3
>> "David".upcase
=> "DAVID"
Ruby’s object model
• (Almost) Everything is an object • including classes
• Objects are instances of classes • but are “teachable” individually
• The class hierarchy descends from Object and BasicObject
• BasicObject is barebones • Object is equipped with a good handful of
methods (functionality)
Instantiating an object
object = Object.new
puts object.object_id
=> 2156388440
Sending messages to objects
• AKA calling methods on objects – methods get called when a message is understood by the
object • Dot notation
string = "Sample string" # A String object
puts string.upcase
=> SAMPLE STRING
puts string.reverse
=> gnirts elpmaS
“Teaching” an object
• Individual objects can be "taught" singleton methods • Singleton methods are callable only on the one object
– not on other objects of that object's class
object = Object.new
def object.talk
puts "Good afternoon from an object"
end
object.talk
=> Good afternoon from an object
Writing your own classes
class Person
def talk
puts "Good afternoon from a Person"
end
end
david = Person.new
david.talk
=> Good afternoon from a Person
The initialize method class Person
def initialize(name)
# Save the incoming name in an instance variable
@name = name
end
def talk
# Reuse the instance variable later
puts "Good afternoon from #{@name}."
end
end
david = Person.new("David")
david.talk
=> Good afternoon from David
Class methods
• A cousin of "static" methods in other languages class Person
def Person.planet
"Earth"
end
end
puts "People live on #{Person.planet}."
=> People live on Earth.
Inheritance
• Ruby supports single inheritance only – (More complex modeling available via modules)
class Animal
def planet
"Earth"
end
end
class Human < Animal
end
h = Human.new
puts h.planet => Earth
Modules
• Like classes, but don't have instances • Can be "mixed in" to classes
– mix-ins add functionality – instances of the class can use methods from the mix-ins
Module example
module Vocal
def talk
puts "Greetings"
end
end
class Person
include Vocal # Mix in the Vocal module
end
david = Person.new
david.talk
=> Greetings
Variables
Local: a = 1
Instance: @a = 1
Global: $a = 1
Class: @@a = 1
Local variables
• Scoped to a class definition, module definition, or method definition
• Outside of the above, they function as "top-level" variables
Three separately-scoped a variables
a = "top-level variable a"
def my_method
a = 2
end
class MyClass
a = 3
end
puts a
=> top-level variable a
Instance variables • For saving state in an object
class Person def initialize(name) @name = name end def talk puts "Good afternoon from #{@name}." end end david = Person.new("David") david.talk => Good afternoon from David
Global variables
• For the most part, don't create them • Some handy built-in ones
– $: the library load path – $/ the input record separator – $$ id of current process – $? the result of most recent system command call – $1, $2, $3…. parenthetical captures from most recent regular
expression match
Class variables
• Scoped per class hierarchy • Shared by classes and their instances
class Human
@@planet = "Earth" # Used at class-level
def planet
@@planet # Used at instance-level
end
end
Constants
• Start with capital letter • Used for names of classes and modules • Also defined inside classes and modules • Not totally constant…
– Can be redefined (but you get a warning) • Resolved with :: operator class Person
PLANET = "Earth"
end
puts Person::PLANET
=> Earth
Booleans and nil
• true and false are objects • nil is an object • Every object has a boolean value
– the boolean value of false and nil is false – the boolean value of everything else is true
if 0
puts "Zero is true in Ruby!"
end
=> Zero is true in Ruby!
String basics
• Single- or double-quoted: – Double allows escape sequences like \n
• Can be upcased, reversed, swapcased, centered, chomped, stripped of whitespace, etc.
• Double-quoted strings allow interpolation of arbitrary code, using #{…} construct:
puts "Two plus two is #{2 + 2}."
=> Two plus two is 4.
String manipulation examples
string = "Sample string"
string.upcase => "SAMPLE STRING"
string.downcase => "sample string"
string.swapcase => "sAMPLE STRING"
string.delete("a-m") => "Sp strn"
string.bytes => [83, 97, 109, 112, …, 110, 103]
string.next => "Sample strinh"
string.start_with?("Sam") => true
string.clear => ""
Array basics
• Literal array constructor: [1,2,3] • Array indexing: a = ["one", "two", "three", "four", "five"]
a[0] => "one"
a[-1] => "five"
• Two elements starting at index 1: a[1,2] => ["two", "three"]
Array manipulation
a = ["one", "two", "three", "four", "five"] a.first => "one"
a.last => "five"
a.reverse
a.pop => "five" (array is now four elements)
a.push("five") => (back to five elements)
a.index("three") => 2
a.count("two") => 1
a.values_at(1,3) => ["two", "four"]
Array iteration
• Uses iterators – methods that take a code block
• Control is yielded to the code block from the method
Iterating with each
a = ["one", "two", "three", "four", "five"]
a.each {|item| puts item.upcase }
=> ONE
TWO
THREE
FOUR
FIVE
Selecting subarrays with select
a = ["one", "two", "three", "four", "five"]
a.select {|item| item.size > 3 }
=> ["three", "four", "five"]
• The opposite of select is reject.
Boolean iterators
a = ["one", "two", "three", "four", "five"]
a.any? {|item| item.size > 5 } => false
a.all? {|item| item.size < 6 } => true
a.one? {|item| item == "four" } => true
a.none? {|item| item == "one" } => false
Mapping an array across a function
a = ["one", "two", "three", "four", "five"]
a.map {|item| item.upcase }
=> ["ONE", "TWO", "THREE", "FOUR", "FIVE"]
Alternate notation: do/end
a.map do |item|
item.upcase
end
• do/end often used for multi-line code blocks
– but there's no rule about it • Precedence of {} is higher
– but you usually don't have to worry about that
What exactly is an iterator?
• A method that yields control to a code block • The code block is part of the method-call syntax • The yielding of control is done with the yield keyword
Fibonacci example
def fib_calculator(n = 10)
a,b = 1,1
n.times do
yield a a,b = b,a+b
end
end
fib_calculator(5) do |fib| puts "Next fib is #{fib}"
end
Next fib is 1 Next fib is 1 Next fib is 2 Next fib is 3 Next fib is 5
Hashes
• Keyed "dictionary" data structures • Keys are unique • Hashes are ordered by order of key insertion • Created with literal constructor {…} • Dereferenced with […] operator
Hash examples
states = { "NY" => "New York",
"NJ" => "New Jersey",
"CT" => "Connecticut" }
states["NY"] => "New York"
states.has_key?("PA") => false
states.select {|abbrev, state| state.size > 8 }
=> {"NJ"=>"New Jersey", "CT"=>"Connecticut"}
states.update({"PA" => "Pennsylvania"})
=> {"NY"=>"New York", "NJ"=>"New Jersey", "CT"=>"Connecticut",
"PA"=>"Pennsylvania"}
Ruby's method/operators (operator overloading)
• Lots of infix and other operators in Ruby are actually methods – including + - * / | ^ [] …
• Equivalencies: 1 + 1 1.+(1) 10 * 3 10.*(3) array[2] array.[](2) array[2] = 1 array.[]=(2,1) • If you define one of these operators in your own classes,
you get the "syntactic sugar" for free
Symbols
• Start with a colon: :x, :sym, :"symbol with spaces" • Programmer interface to Ruby's internal symbol table • One symbol per identifier in the running program
– plus any that you create as symbols • Used a lot as hash keys
– faster lookup than strings
Regular expressions and pattern matching
• Regular expressions are first-class objects • Literal constructor: /…/ • Basic matches use the match method or the =~ operator • match returns an instance of the MatchData class • =~ returns the offset of the match, or nil if no match
MatchData objects
string = "New Jersey is a state."
regex = /New (\S+)/
m = regex.match(string)
m.string => "New Jersey is a state."
m.captures => ["Jersey"]
m[0] => "New Jersey"
m[1] => "Jersey"
m.pre_match => ""
m.post_match => " is a state."
Scanning strings
string = "New York|New Jersey|Connecticut"
regex = /[^|]+/
string.scan(regex) => ["New York", "New Jersey", "Connecticut"]
string.scan(regex) do |state|
puts "Next state in list is #{state}."
end
=> Next state in list is New York.
Next state in list is New Jersey.
Next state in list is Connecticut.
String substitution
• One substitution: string = "New York"
string.sub(/New/, "Old") => "Old York"
• Global substitution: string = "New York, New Jersey"
string.gsub(/New/, "Old")
=> "Old York, Old Jersey"
• With back-references: string.gsub(/(New)/, "Very \\1") => "Very New York, Very New Jersey"
Function objects (Procs)
func = Proc.new {|x| x * 10 }
func.call(3) => 30
• Use a Proc object instead of a code block, with the special &-notation:
map_func = Proc.new {|str| str.upcase.reverse }
["New York", "New Jersey"].map(&map_func)
=> ["KROY WEN", "YESREJ WEN"]
• Symbols automatically work with the &-notation: ["New York", "New Jersey"].map(&:upcase)
=> ["NEW YORK", "NEW JERSEY
Basic keyboard I/O
• print just prints; puts adds a newline
print "Your name: "
name = gets.chomp
puts "Welcome, #{name}!"
File reading
• Content available via gets or via iteration (each, map, etc.)
File.open("myfile") do |fh|
first_line = fh.gets
puts "First line: #{first_line}"
fh.each do |line|
puts "Next line: #{line}"
end
end
full_text = File.read("myfile")
array_of_lines = File.readlines("myfile")
File writing
File.open("myfile", "w") do |fh|
fh.puts "Line one!"
end
Stdlib: open-uri
require 'open-uri'
text = open("http://www.google.com")
puts text.read => content of Google
Stdlib: tempfile
• Creates a unique filename • Opens a file for you in your system's temp directory (e.g.,
/tmp, /var/folders, etc.) • You specify
– a prefix for the filename – an optional directory (to override tempfile's choice)
require 'tempfile'
tf = Tempfile.new("my_prefix", "/Users/dblack/tmp")
tf.puts("hi") # etc.
Stdlib: scanf
• Based on the scanf(3) system call • Takes a format string and parses a string • Converts the results based on the format string
require 'scanf'
string = "David 55"
string.scanf("%s,%d") => ["David", 55]
• Can also take a code block – successive scans are yielded to the block
Stdlib: FileUtils
• Methods based on Unix file- and directory-related commands
require 'fileutils'
FileUtils.mkdir_p("/tmp/a/b/c")
FileUtils.rm_rf("/tmp/a")
FileUtils.ln_s("source", "destination")
FileUtils.touch("/tmp/abc")
Stdlib: prime
require 'prime'
Prime.prime?(3) => true
Prime.first(5) => [2, 3, 5, 7, 11]
Prime.take_while do |n|
n < 100
end => [2, 3, 5, …, 83, 89, 97]
Further learning
• Ruby home page: – http://www.ruby-lang.org
• Ruby Central (events, community, initiatives): – http://rubycentral.org
• Ruby documentation: – http://www.ruby-doc.org
• The Well-Grounded Rubyist, second edition: – http://www.manning/black3
Questions?
Thank you!
ACM Learning Webinar
David A. Black Lead Developer
Cyrus Innovation
March 27, 2014
ACM: The Learning Continues…
• Questions about this webcast? learning@acm.org
• ACM Learning Webinars (on-demand archive): http://learning.acm.org/webinar • ACM Learning Center: http://learning.acm.org • ACM SIGPLAN: http://www.sigplan.org/
• ACM Queue: http://queue.acm.org
• Ruby Learning Path: http://learning.acm.org/path/ruby/
61
top related