Housekeeping Welcome to today s ACM Webinar. The presentation - - PowerPoint PPT Presentation

housekeeping
SMART_READER_LITE
LIVE PREVIEW

Housekeeping Welcome to today s ACM Webinar. The presentation - - PowerPoint PPT Presentation

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 W indow s , Com m and +


slide-1
SLIDE 1

“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 W indow s, Com m and + 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 autom atic e-m ail notification when the recording is ready.

1

slide-2
SLIDE 2

Ruby for the Nuby

ACM Learning Webinar David A. Black Lead Developer Cyrus Innovation March 27, 2014

slide-3
SLIDE 3
  • 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

slide-4
SLIDE 4

“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 W indow s, Com m and + 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 autom atic e-m ail notification when the recording is ready.

4

slide-5
SLIDE 5

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!

slide-6
SLIDE 6

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)
slide-7
SLIDE 7

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)
slide-8
SLIDE 8

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!

slide-9
SLIDE 9

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.

slide-10
SLIDE 10

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"

slide-11
SLIDE 11

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)

slide-12
SLIDE 12

Instantiating an object

  • bject = Object.new

puts object.object_id => 2156388440

slide-13
SLIDE 13

Sending messages to objects

  • AKA calling methods on objects

– methods get called when a message is understood by the

  • bject
  • Dot notation

string = "Sample string" # A String object puts string.upcase => SAMPLE STRING puts string.reverse => gnirts elpmaS

slide-14
SLIDE 14

“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

  • bject = Object.new

def object.talk puts "Good afternoon from an object" end

  • bject.talk

=> Good afternoon from an object

slide-15
SLIDE 15

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

slide-16
SLIDE 16

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

slide-17
SLIDE 17

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.

slide-18
SLIDE 18

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

slide-19
SLIDE 19

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

slide-20
SLIDE 20

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

slide-21
SLIDE 21

Variables

Local: a = 1 Instance: @a = 1 Global: $a = 1 Class: @@a = 1

slide-22
SLIDE 22

Local variables

  • Scoped to a class definition, module definition, or method

definition

  • Outside of the above, they function as "top-level" variables
slide-23
SLIDE 23

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

slide-24
SLIDE 24

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

slide-25
SLIDE 25

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

slide-26
SLIDE 26

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

slide-27
SLIDE 27

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

slide-28
SLIDE 28

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!

slide-29
SLIDE 29

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.

slide-30
SLIDE 30

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 => ""

slide-31
SLIDE 31

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"]

slide-32
SLIDE 32

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"]

slide-33
SLIDE 33

Array iteration

  • Uses iterators

– methods that take a code block

  • Control is yielded to the code block from the method
slide-34
SLIDE 34

Iterating with each

a = ["one", "two", "three", "four", "five"] a.each {|item| puts item.upcase } => ONE TWO THREE FOUR FIVE

slide-35
SLIDE 35

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.
slide-36
SLIDE 36

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

slide-37
SLIDE 37

Mapping an array across a function

a = ["one", "two", "three", "four", "five"] a.map {|item| item.upcase } => ["ONE", "TWO", "THREE", "FOUR", "FIVE"]

slide-38
SLIDE 38

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

slide-39
SLIDE 39

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
slide-40
SLIDE 40

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

slide-41
SLIDE 41

Hashes

  • Keyed "dictionary" data structures
  • Keys are unique
  • Hashes are ordered by order of key insertion
  • Created with literal constructor { …

}

  • Dereferenced with [ …

] operator

slide-42
SLIDE 42

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"}

slide-43
SLIDE 43

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

slide-44
SLIDE 44

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

slide-45
SLIDE 45

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
slide-46
SLIDE 46

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."

slide-47
SLIDE 47

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.

slide-48
SLIDE 48

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"

slide-49
SLIDE 49

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

slide-50
SLIDE 50

Basic keyboard I/ O

  • print just prints; puts adds a newline

print "Your name: " name = gets.chomp puts "Welcome, #{name}!"

slide-51
SLIDE 51

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")

slide-52
SLIDE 52

File writing

File.open("myfile", "w") do |fh| fh.puts "Line one!" end

slide-53
SLIDE 53

Stdlib: open-uri

require 'open-uri' text = open("http://www.google.com") puts text.read => content of Google

slide-54
SLIDE 54

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.

slide-55
SLIDE 55

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

slide-56
SLIDE 56

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")

slide-57
SLIDE 57

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]

slide-58
SLIDE 58

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

slide-59
SLIDE 59

Questions?

slide-60
SLIDE 60

Thank you!

ACM Learning Webinar David A. Black Lead Developer Cyrus Innovation March 27, 2014

slide-61
SLIDE 61

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