lecture 1 - seas.upenn.educis196/lectures/cis196-2018s-lecture1.pdfcis 120 (or instructor ... one...

54
Lecture 1 Basic Ruby 1 / 54

Upload: donhan

Post on 15-Jun-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Lecture 1

Basic Ruby

1 / 54

What does this do?3.times do print 'Hello, world!'end

2 / 54

Why Ruby?Optimized for programmer happiness

Used for Ruby on Rails

Very popular web framework

3 / 54

Course Policies

4 / 54

PrerequisitesCIS 120 (or instructor permission)

Basic HTML/CSS knowledge

Codecademy

Mozilla Developer Network

W3Schools

Please speak with me if you do not have theprerequisites or have any other concerns

5 / 54

CIS 19x Course Structure4 shared lectures during semester

1/17: Command Line

1/24: Version Control & Git

1/31: History of the Internet & How the Webworks

2/7: HTML & CSS

Learn about language in "recitation" sections

6 / 54

CIS 196 Course StructureLecture Topics:

3 weeks on Ruby programming language

6 weeks on Ruby on Rails web framework

5 weeks on miscellaneous topics

9 homework assignments

1 final project

For more details, read the course syllabus

7 / 54

Grading70% - Homework

25% - Final Project

5% - In-class Participation

8 / 54

HomeworkDue on Tuesdays at 11:59pm through GitHubClassroom

Unlimited submissions

Your latest submission will be used for grading

One free late day to use on any assignment

After, 20% will be deducted for each day late

9 / 54

Correctness (15 pts) Full credit if you pass alltests on Travis CI (unlesstold otherwise)

Style (5 pts) Full credit if you have noRubocop offenses

Best Practices (5 pts) TAs will manually gradeyour code to ensure theRuby Way

Homework Grading

10 / 54

Final ProjectMust be a web app built using Ruby on Rails

Must be approved by me ahead of time

Milestones to help keep you on track

Will be "due" the last day of class

Demo on one of the Reading Days at the ProjectFair

11 / 54

In-class ParticipationAttending and participating in lectures will bevery beneficial for you

To help encourage you to come to class, we willuse Poll Everywhere during class

Polls will be scattered throughout lecture

You will receive participation grade based on:

Completing polls while in class

Correctness of answers

12 / 54

Academic IntegrityDon't copy/paste others' code

Don't have mid-level discussions

High-LevelDiscussion

What is Rails used for?

Mid-Level Discussion How did you do Homework 1?Low-LevelDiscussion

What is the syntax foriterators?

13 / 54

Tentative O�ce HoursWeekday Time Location TA

Sunday 2-3pm Moore 100 DesmondMonday 4:30-6:30pm Moore 100 SanjanaTuesday 3-4pm Moore 100 Zhilei

4-5pm Moore 100 Desmond7-8pm Moore 100 Jackie

Wednesday 7-8pm Moore 100 JackieThursday 3:30-4:30pm Moore 100 Zhilei

14 / 54

Course WebsitesCIS 196 Website - All relevant course info

Piazza - All course discussions & communication

GitHub - Homework assignment management

Travis CI - Results of tests run on submission

Note that we will be using travis-ci.com

Canvas - Viewing grades

15 / 54

Ruby

16 / 54

What you'll needText editor (Sublime Text is probably easiest)

Command Line

If you use Windows, you must use a Linux VM ordual boot Linux

I have provided a VM here with Ruby and Railspre-installed

If you run Ruby on Windows, I nor your TAswill debug for you

Ruby

17 / 54

Installing RubyUse the Ruby Version Manager (RVM) to manageand install Ruby versions

Use this even if you plan on just using oneversion

In this class, we will be using version 2.4.1

Make sure you download the correct version

18 / 54

ResourcesUse the Ruby Docs whenever you get stuck

Make sure you're looking at the correct version(2.4.1)

This class will follow this style guide

10 points of your homework grade come fromstyle and best practices

5 of which come from Rubocop (more onthis later)

19 / 54

History of RubyRuby was designed in the mid-90s by Yukihiro"Matz" Matsumoto

Influenced by Perl, Smalltalk, Eiffel, Ada & Lisp(Matz's favorite languages)

Achieved mass acceptance in 2006

Much of Ruby's success and growth can beattributed to Rails

Read about Matz's inspiration for Ruby here

20 / 54

Running RubyUse a REPL (Read-Execute-Print-Loop) with the irbcommand in terminal

Allows you to write and execute Ruby codefrom the Command Line

This is great for testing

Get out of the REPL by entering quit

Execute .rb files with the ruby command:

ruby file.rb

21 / 54

Types in RubyAlmost everything in Ruby is an object

Ruby is strongly typed

Every object has a fixed type

Ruby is dynamically typed

Variables do not need to be initialized

Compare to Java which is statically typed

22 / 54

Printing in RubyYou can print a value with three differentcommands: print, puts, and p

print outputs the value and returns nil

puts outputs the value with a newline andreturns nil

p both outputs and returns the value

I'll use p in my examples since it formatsoutput better

I will denote output with #=>

p 'hello world' #=> "hello world"

23 / 54

NumericsThere are several types of numbers in Ruby

Unlike Java, numbers are also objects in Ruby

The main ones you'll be using are instances of theInteger and Float classes

This is helpful to know when looking at theRuby Docs

If you see anything about FixNum or BigNum, notethat they were deprecated in Ruby 2.4

24 / 54

Local VariablesSince Ruby is dynamically typed, you don't need todeclare types (like int, String, etc.)

Local variables are assigned to bare words

foo = 100p foo #=> 100

25 / 54

StringsStrings can be denoted with either single ordouble quotes

They can be concatenated together with + andappended with <<

hello = 'Hello'world = 'world!'foo = hello + ', ' + worldp foo #=> "Hello, world!"p hello #=> "Hello"hello << '!'p hello #=> "Hello!"

Note that concatenation did not change the variable, but appending

did

26 / 54

Escaped Characters only work in DoubleQuotes

print 'hello\nworld'#=> hello\nworld

print "hello\nworld"#=> helloworld

27 / 54

Only Double Quotes support StringInterpolation

When inserting variables into strings, stringinterpolation is preferred

Put local variable betwen the curly braces in #{}

This calls to_s on the variable

foo = 5p "Hello, #{foo}!" #=> "Hello, 5!"

# Compare to:p 'Hello, ' + foo.to_s + '!' #=> "Hello, 5!"

28 / 54

When to use Single Quotes vs. DoubleQuotes

Use double quotes if:

You're using escaped characters or stringinterpolation

You want to include single quotes in the string

In all other cases, use single quotes

It makes for more readable code

29 / 54

SymbolsDenoted with a colon in front

They are immutable

For example, you cannot do :a << :b becausethat would change :a

They are unique

The equal? method checks if the two objects arethe same

'hi'.equal? 'hi' #=> false:hi.equal? :hi #=> true

30 / 54

Boolean StatesAll Ruby objects have boolean states of either trueor false

In fact, the only two objects in Ruby that are falseare nil and false itself

nil is an object that represents nothingness

Kind of like Java's null

31 / 54

If StatementsConditionals can be used for control flow and toreturn different values based on the condition

They implicitly return the last evaluatedexpression

Use the elsif keyword for more branching

foo = if true 1 elsif false 2 else 3 endp foo #=> 1

32 / 54

Unless StatementsEvaluated when the condition is false

Equivalent to if not

Note that you should never have an unlessstatement followed by an else

Instead, use an if ... else flow

unless false p 'hello'end#=> "hello"

33 / 54

Conditional Modi�ersif and unless can be placed at the end of the line

This helps code read more like English

These are prefered for one liners

p 'hello' if true #=> "hello"p 'bye' unless false #=> "bye"

34 / 54

Ternary OperatorWhen using one line if-else statements, favor theternary operator

p true ? 'hello' : 'goodbye' #=> "hello"p false ? 'hello' : 'goodbye' #=> "goodbye"

35 / 54

MethodsParentheses around arguments can be omitted ifunambiguous

Our Style Guide has a lot to say about methods& parentheses

def hi 'hello, there'end

def hello(name) puts "hello, #{name}"end

puts hi #=> "hello, there"hello('Matz') #=> "hello, Matz"hello 'DHH' #=> "hello, DHH"

36 / 54

Implicit ReturnsMethods in Ruby always return exactly one thing

They will return the last executed expression

This means that you do not have to explicitly typereturn x at the end of the method

Only use the return keyword when you want to exita method early

37 / 54

Method NamesWhile not strictly enforced, Ruby has certainconventions with naming methods

If a method ends in:

?, it should return a boolean (e.g. Array#empty?)

=, it should write to a variable (e.g. writermethods)

!, it should potentially change the variablebeing called on or perform some otherdangerous action (e.g. String#capitalize!)

You will encounter each kind as the courseprogresses

38 / 54

Default ArgumentsDenoted with an equal sign and value in methodsignature

Optional when calling method

def hello(name = 'world') p "Hello, #{name}"end

hello #=> "Hello, world"hello('Matz') #=> "Hello, Matz"

39 / 54

# bad def foo(bar) if bar p 'hello' p 'goodbye' end end

# good def foo(bar) return unless bar p 'hello' p 'goodbye' end

Guard ClausesInstead of wrapping an entire method in aconditional, use a guard clause to exit early

40 / 54

ArraysInstantiated with [] or Array.new, but [] is preferred

Note that you don't have to specify a size

Arrays are heterogeneous

Elements can be of different types

The shovel operator << is the preferred way to addelements to the end of an array

a = []a << 1p a #=> [1]

41 / 54

IteratorsThere are for ... in loops in Ruby, but they arediscouraged

You will never have to use one in this class

The Ruby Way is to use iterators

The most basic one is the each iterator

foo = [1, 2, 3]foo.each do |num| print "#{num} "end#=> "1 2 3 "

42 / 54

BlocksThis is the code between the do and end keywords

It is convention to use the do ... end keywordswhen the block spans multiple lines

But they should be replaced by { } when themethod is only one line long

Or a method is being chained off of the block

[1, 2, 3].each { |n| print "#{n} " } #=> "1 2 3 "p [1, 2, 3].map { |n| n + 1 }.join(' ') #=> "2 3 4"

43 / 54

HashesUsed to store key-value pairs

Like maps in Java

Instantiated with {} and Hash.new but {} is preferred

Keys can be ANY object

They're often symbols

Values can be accessed with []

foo = {}foo[:hello] = 'world'p foo #=> {:hello=>"world"}p foo[:hello] #=> "world"

44 / 54

Alternate Hash Syntax=> is called a hash rocket

It is the default notation linking key and value

Starting with Ruby 2.0, an alternate syntax can beused

Only when the key is a symbol

This syntax is preferred if all keys are symbols

foo = { foo: 'bar', baz: 'foobar'}p foo #=> {:foo=>"bar", :baz=>"foobar"}

45 / 54

Managing Dependencies

46 / 54

GemsRuby libraries are called gems

The command to install them in gem install gem_name

When installed, the gem is installed in the currentRuby version's gem directory

To use a gem, pass the name of the gem as a stringto the require method at the top of the file (e.g.require pry)

47 / 54

The Bundler GemBundler is used to manage dependencies, comes inhandy in large projects

Install the gem using gem install bundler

To use, create Gemfile in the directory & add gemsto it

Run bundle install or bundle for short to install allgems in the Gemfile

48 / 54

The Pry GemA very useful gem for debugging

gem install pry and add require pry to the top of thefile

Insert the line binding.pry in a Ruby file

When you run the program, Ruby will stop atthat line and give you a REPL with all variablesin scope

binding.pry must be deleted from yourhomework assignments before submittingbecause it will cause your tests to fail

49 / 54

The Rubocop GemRubocop will be used to grade for Style

To run Rubocop:

1. Install Rubocop by running gem install rubocop

2. Make sure that you're in the directory that youwant to check

3. Run rubocop

50 / 54

The RSpec GemRSpec will be used for testing

Be sure to run gem install rspec

You will learn more about RSpec and writing testsin 2 lectures

For now, you will be able to run pre-written testsby running rspec from the Command Line

51 / 54

Homework 1

52 / 54

Homework 1Released now, due next Tuesday at 11:59pm

When you get started, you'll want to run gem installbundler and bundle install

You can run rspec at any time during developmentto see how you're doing against the test cases

You can run rubocop at any time to see how you'redoing on style

This means that you don't have to submit everytime you want to see your output

53 / 54

Homework 1You will:

Set up everything you need to get started withRuby

Complete 5 methods designed to get you morecomfortable with Ruby

Submit to GitHub Classroom & view results onTravis CI

You will fill out exercises.rb

There is a provided file called bin/console.rb thatwill execute your code

You can run ruby bin/console.rb and call all of themethods that you defined in exercises.rb

54 / 54