Introduction - Penn Engineeringcis196/lectures/CIS196-2019s-lecture1… · Rubocop offenses Best Practices (5 pts) TAs will manually grade your code to ensure the Ruby Way Hom ework

Post on 27-Sep-2020

0 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

Lecture 1

Introduction

1 / 57

What is this course about?Ruby language

web development using Ruby on Rails

database design, API usage and integration,complex front-end design (UI/UX)

popular software architecture patterns

how the web works: internet's client-server model

version control (Git) amongst other topics

2 / 57

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

3 / 57

Why Ruby?Optimized for programmer happiness

Used for Ruby on Rails

Very popular web framework

4 / 57

Course Policies

5 / 57

PrerequisitesCurrently taking CIS 120 or have already taken it(or instructor permission)

Basic HTML/CSS knowledge

Codecademy

Mozilla Developer Network

W3Schools

Good to know: tag, basic syntax, important tagse.g. <h1>

Let us know if you do not have the prerequisitesor have any other concerns

6 / 57

CIS 196 Course StructureLecture Topics:

3 weeks on Ruby programming language

6 weeks on Ruby on Rails web framework

3 weeks on miscellaneous topics

9 homework assignments

1 final project

For more details, read the course syllabus

7 / 57

CIS 19x Course Schedule3 shared lectures during semester

1/23: Command Line

1/30: git/github

2/6: HTML/CSS basics

8 / 57

Grading70% - Homework

25% - Final Project

5% - In-class polls

9 / 57

HomeworkDue on Wednesdays at noon through GitHubClassroom

2 free late days to use on any assignment

After, 20% will be deducted for each day late

We give you all our automated tests

Unlimited submissions

Your latest submission will be used for grading

10 / 57

Correctness (15 pts) Full credit if you pass allour automated tests onTravis CI

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

11 / 57

Final ProjectMust be a web app built using Ruby on Rails

Must be an idea approved by either of us ahead oftime

Milestones included to keep you on track

Demo to both instructors during Reading Days.

Project is due the day of the demo

12 / 57

In-class ParticipationWe'll use Poll Everywhere during class

Polls will be scattered throughout lecture

You will receive 5% of your grade based oncompleting polls

13 / 57

Poll EverywhereGet started by going tohttps://pollev.com/cis196776

When asked to provide a screen name, make ityour preferred first name followed by your lastname

14 / 57

Academic IntegrityDon't copy/paste others' code

Don't have mid-level discussions

High-Level Discussion What is Rails used for?Mid-Level Discussion How did you do Homework 1?Low-Level Discussion What is the syntax for iterators?

15 / 57

Tentative O�ce HoursWeekday Time TA

Monday 5-7pm SanjanaMonday 7-9pm DesmondTuesday 7:30-9:30pm ZhileiWednesday 7-9pm ZenaThursday 8-10pm EdwardSunday 8-9pm Zena

Office hour locations will be announced soon.

16 / 57

Piazza sign upPiazza sign up

17 / 57

Course WebsitesCIS 196 Website - All relevant course info

Piazza sign up - All course discussions &communication

GitHub - HW repos and submission

Travis CI - Results of tests run on submission

Note that we will be using travis-ci.com

Canvas - Viewing grades

18 / 57

Ruby

19 / 57

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

We have provided a VM here with Ruby andRails pre-installed

Ruby

20 / 57

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

Make sure you download the correct version

21 / 57

ResourcesUse the Ruby Docs whenever you get stuck

Make sure you're looking at the correct version(2.5.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 which is ourstyle checker

22 / 57

History of RubyRuby was designed in the 90s by a Japeneseprogrammer, Yukihiro "Matz" Matsumoto

Influenced by Perl, Ada and other scriptinglanguages (Matz's favorite languages)

Achieved mass acceptance in mid-2000's

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

Read about Matz's inspiration for Ruby here

23 / 57

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

24 / 57

Types in RubyRuby 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

Almost everything in Ruby is an object

25 / 57

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"

26 / 57

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

27 / 57

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

28 / 57

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 appendingdid

29 / 57

Escaped Characters only work in DoubleQuotes

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

print "hello\nworld"#=> helloworld

30 / 57

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

31 / 57

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

32 / 57

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 for referentialequality

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

33 / 57

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

34 / 57

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

Use the elsif keyword for more branching

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

35 / 57

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"

36 / 57

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"

37 / 57

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

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

38 / 57

MethodsMethod signature in the form of defmethod_name(arg1, arg2, ...) followed by end keyword

In method calls, parentheses around argumentscan be omitted if unambiguous

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" 39 / 57

Implicit ReturnsMethods in Ruby always return exactly one thing

They will return the return value from the lastexecuted 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

40 / 57

# 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

41 / 57

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

Methods are written in snake_case

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 perform an operation inplace onthe object it's being called on (e.g.String#capitalize!)

You will encounter each kind as the courseprogresses

42 / 57

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"

43 / 57

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]

44 / 57

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 "

45 / 57

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"

46 / 57

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"

47 / 57

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

48 / 57

Managing Dependencies

49 / 57

GemsRuby libraries are called gems

The command to install a specific gem is: geminstall 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)

You can specify all the gems you want someoneusing your code to install by creating a Gemfile inthe directory of your code

Lists all gems you should install

50 / 57

The Bundler GemBundler is used to manage other gems(dependencies), comes in handy in large projects

Install the gem using gem install bundler

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

51 / 57

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

52 / 57

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

53 / 57

The RSpec GemRSpec will be used for testing

Be sure to run gem install rspec

You will learn more about RSpec and be able tounderstand our tests in a couple of weeks

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

54 / 57

Homework 1

55 / 57

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

56 / 57

Homework 1Released after class, due next Wednesday 1/30 atnoon

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

57 / 57

top related