Lecture 1. Basic Ruby 1 / 61

Similar documents
Lecture 2. Object Orientation 1 / 50

Lecture 2. Object Orientation 1 / 51

Lecture 3. Miscellaneous Ruby and Testing 1 / 48

Lecture 3. Miscellaneous Ruby and Testing 1 / 40

Lecture 2. Object Orientation

Lecture 3. Miscellaneous Ruby and Testing

CIS192: Python Programming

Ruby: Introduction, Basics

CIS192 Python Programming. Robert Rand. August 27, 2015

Ruby: Introduction, Basics

Lecture 4. Ruby on Rails 1 / 52

Computer Science Seminar. Whats the next big thing? Ruby? Python? Neither?

CSE : Python Programming

CSE 341, Autumn 2015, Ruby Introduction Summary

Java Bytecode (binary file)

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Your First Ruby Script

Ruby: Introduction, Basics

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

CS 5142 Scripting Languages

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

PHP. Interactive Web Systems

CS 241 Data Organization using C

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Overview of the Ruby Language. By Ron Haley

15.1 Origins and Uses of Ruby

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

CIS 3308 Web Application Programming Syllabus

Lecture 8. Validations & Sessions 1 / 41

Ruby. Mooly Sagiv. Most slides taken from Dan Grossman

San José State University Computer Science CS 122 Advanced Python Programming Spring 2018

Accelerating Information Technology Innovation

CS 241 Data Organization. August 21, 2018

CS11 Java. Fall Lecture 1

KOMAR UNIVERSITY OF SCIENCE AND TECHNOLOGY (KUST)

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Lecture 1. Course Overview Types & Expressions

CSC 326H1F, Fall Programming Languages. What languages do you know? Instructor: Ali Juma. A survey of counted loops: FORTRAN

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

Lecture 14. Moving Forward 1 / 23

Announcements. 1. Forms to return today after class:

Intro. Scheme Basics. scm> 5 5. scm>

CS 106 Introduction to Computer Science I

Computer Science II Lecture 1 Introduction and Background

Installation Download and installation instructions can be found at

CS 11 java track: lecture 1

CS 231 Data Structures and Algorithms, Fall 2016

INFS 2150 (Section A) Fall 2018

Introduction to Ruby on Rails

CS143 Handout 05 Summer 2011 June 22, 2011 Programming Project 1: Lexical Analysis

CS : Programming for Non-majors, Fall 2018 Programming Project #2: Census Due by 10:20am Wednesday September

Introduction to Ruby. SWEN-250 Personal Software Engineering

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Introducing: main Function, Comments, Statements

Introduction CMSC 330: Organization of Programming Languages. Books on Ruby. Applications of Scripting Languages

Pace University. Fundamental Concepts of CS121 1

Ruby: Objects and Dynamic Types

Functions. Nate Foster Spring 2018

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

CGS 3066: Spring 2015 JavaScript Reference

Introduction to Ruby on Rails

CSC 172 Data Structures and Algorithms. Fall 2017 TuTh 3:25 pm 4:40 pm Aug 30- Dec 22 Hoyt Auditorium

Ruby on Rails Welcome. Using the exercise files

Object-Oriented Programming for Managers

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Language Proposal: tail

CS503 Advanced Programming I CS305 Computer Algorithms I

Key Differences Between Python and Java

Introduction. CSC 440: Software Engineering Slide #1

CS 240 Fall Mike Lam, Professor. Just-for-fun survey:

S206E Lecture 19, 5/24/2016, Python an overview

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CS252 Advanced Programming Language Principles. Prof. Tom Austin San José State University Fall 2013

Lists, loops and decisions

CS31 Discussion 1E. Jie(Jay) Wang Week1 Sept. 30

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 9: OCT. 4TH INSTRUCTOR: JIAYIN WANG

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

COMP-520 GoLite Tutorial

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

Welcome to... CS113: Introduction to C

Computer Science 210: Data Structures

Syllabus COSC-051-x - Computer Science I Fall Office Hours: Daily hours will be entered on Course calendar (or by appointment)

Introduction to Ruby on Rails

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

TTh 9.25 AM AM Strain 322

CIS*1500 Introduction to Programming

CS 240 Fall 2015 Section 004. Alvin Chao, Professor

FRAC: Language Reference Manual

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

San Jose State University College of Science Department of Computer Science CS151, Object-Oriented Design, Sections 1, 2, and 3, Spring 2018

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

CS1 Lecture 3 Jan. 18, 2019

Introduction to Programming Using Java (98-388)

Programming Languages and Techniques (CIS120)

Typescript on LLVM Language Reference Manual

by the evening of Tuesday, Feb 6

Transcription:

Lecture 1 Basic Ruby 1 / 61

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

Why Ruby? Optimized for programmer happiness Used for Ruby on Rails Very popular web framework 3 / 61

Course Policies 4 / 61

Prerequisites CIS 120 (or instructor permission) Basic HTML/CSS knowledge Codecademy Mozilla Developer Network W3Schools Please speak with us if you do not have the prerequisites or have any other concerns 5 / 61

CIS 19x Course Structure 3 shared lectures during semester 8/28: Git 9/11: Command Line 9/18: How the Web works Learn about language in "recitation" sections 6 / 61

CIS 196 Course Structure Lecture 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 / 61

Grading 70% - Homework 25% - Final Project 5% - In-class Participation 8 / 61

Homework Due on Thursdays at 11:59pm through GitHub Classroom 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 / 61

Homework Grading Correctness (15 pts) Style (5 pts) Best Practices (5 pts) Full credit if you pass all tests on Travis CI (unless told otherwise) Full credit if you have no Rubocop offenses TAs will manually grade your code to ensure the Ruby Way 10 / 61

Final Project Must be a web app built using Ruby on Rails Must be approved by Desmond/Sanjana 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 Project Fair 11 / 61

In-class Participation Attending and participating in lectures will be very beneficial for you To help encourage you to come to class, we will use Poll Everywhere during class Polls will be scattered throughout lecture You will receive participation grade based on: Completing polls while in class 12 / 61

Poll Everywhere Get started by going to https://pollev.com/cis196776 When asked to provide a screen name, make it your preferred first name combined with your last name Otherwise you won't get points for participating 13 / 61

Which site uses Ruby on Rails? GitHub Piazza Canvas Airbnb All of the above! Poll 14 / 61

Why are you taking this class? Poll 15 / 61

Academic Integrity Don'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? 16 / 61

O ce Hours Weekday Time TA Thursday 5-7pm Desmond Tuesday 7-9pm Sanjana Wednesday 5-7pm Zena Tuesday 6-8pm Edward TBD TBD Zhilei All office hours will be held in Moore 100. 17 / 61

Course Websites CIS 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 18 / 61

Ruby 19 / 61

What you'll need Text editor (Sublime Text is probably easiest) Command Line If you use Windows, you must use a Linux VM or dual boot Linux Ruby We have provided a VM here with Ruby and Rails pre-installed If you run Ruby on Windows, I nor your TAs will debug for you 20 / 61

Installing Ruby Use the Ruby Version Manager (RVM) to manage and install Ruby versions Use this even if you plan on just using one version In this class, we will be using version 2.5.1 Make sure you download the correct version 21 / 61

Resources Use 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 from style and best practices 5 of which come from Rubocop (more on this later) 22 / 61

History of Ruby Ruby 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 be attributed to Rails Read about Matz's inspiration for Ruby here 23 / 61

Running Ruby Use a REPL (Read-Execute-Print-Loop) with the irb command in terminal Allows you to write and execute Ruby code from 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 / 61

Types in Ruby Almost 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 25 / 61

Will this give me an error? int_var = 5 int_var = 'five' Poll 26 / 61

Printing in Ruby You can print a value with three different commands: print, puts, and p print outputs the value and returns nil puts outputs the value with a newline and returns nil p both outputs and returns the value I'll use p in my examples since it formats output better I will denote output with #=> p 'hello world' #=> "hello world" 27 / 61

Numerics There 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 the Integer and Float classes This is helpful to know when looking at the Ruby Docs If you see anything about FixNum or BigNum, note that they were deprecated in Ruby 2.4 28 / 61

Local Variables Since Ruby is dynamically typed, you don't need to declare types (like int, String, etc.) Local variables are assigned to bare words foo = 100 p foo #=> 100 29 / 61

Strings Strings can be denoted with either single or double quotes They can be concatenated together with + and appended with << hello = 'Hello' world = 'world!' foo = hello + ', ' + world p foo #=> "Hello, world!" p hello #=> "Hello" hello << '!' p hello #=> "Hello!" Note that concatenation did not change the variable, but appending did 30 / 61

Escaped Characters only work in Double Quotes print 'hello\nworld' #=> hello\nworld print "hello\nworld" #=> hello world 31 / 61

Only Double Quotes support String Interpolation When inserting variables into strings, string interpolation is preferred Put local variable betwen the curly braces in #{} This calls to_s on the variable foo = 5 p "Hello, #{foo}!" #=> "Hello, 5!" # Compare to: p 'Hello, ' + foo.to_s + '!' #=> "Hello, 5!" 32 / 61

When to use Single Quotes vs. Double Quotes Use double quotes if: You're using escaped characters or string interpolation You want to include single quotes in the string In all other cases, use single quotes It makes for more readable code 33 / 61

Which has the best Ruby style? Poll '5 + 5 = ' + (5 + 5).to_s "5 + 5 = 10" "5 + 5 = #{5 + 5}" 34 / 61

Symbols Denoted with a colon in front They are immutable For example, you cannot do :a << :b because that would change :a They are unique The equal? method checks if the two objects are the same 'hi'.equal? 'hi' #=> false :hi.equal? :hi #=> true 35 / 61

Boolean States All Ruby objects have boolean states of either true or false In fact, the only two objects in Ruby that are false are nil and false itself All other objects are true nil is an object that represents nothingness Kind of like Java's null 36 / 61

If Statements Conditionals can be used for control flow and to return different values based on the condition They implicitly return the last evaluated expression Use the elsif keyword for more branching foo = if true 1 elsif false 2 else 3 end p foo #=> 1 37 / 61

Unless Statements Evaluated when the condition is false Equivalent to if not Note that you should never have an unless statement followed by an else Instead, use an if... else flow unless false p 'hello' end #=> "hello" 38 / 61

Conditional Modi ers if 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" 39 / 61

Ternary Operator When using one line if-else statements, favor the ternary operator p true? 'hello' : 'goodbye' #=> "hello" p false? 'hello' : 'goodbye' #=> "goodbye" 40 / 61

Which of these has the best Ruby style? p 'hello' if not 'Desmond'.nil? p 'hello' unless 'Desmond'.nil? p 'Desmond'? ('Sanjana'? 'hello' : 'goodbye') : 'hi' p 'hello' if 'Desmond' Poll 41 / 61

Methods Parentheses around arguments can 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" 42 / 61

Implicit Returns Methods in Ruby always return exactly one thing They will return the last executed expression This means that you do not have to explicitly type return x at the end of the method Only use the return keyword when you want to exit a method early 43 / 61

Method Names While not strictly enforced, Ruby has certain conventions 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. writer methods)!, it should potentially change the variable being called on or perform some other dangerous action (e.g. String#capitalize!) You will encounter each kind as the course progresses 44 / 61

Default Arguments Denoted with an equal sign and value in method signature Optional when calling method def hello(name = 'world') p "Hello, #{name}" end hello #=> "Hello, world" hello('matz') #=> "Hello, Matz" 45 / 61

Guard Clauses Instead of wrapping an entire method in a conditional, use a guard clause to exit early # bad def foo(bar) if bar p 'hello' p 'goodbye' end end # good def foo(bar) return unless bar p 'hello' p 'goodbye' end 46 / 61

What's wrong with this method? def hello(name) return unless name puts "Hello #{name}" puts 'Goodbye' if not name.empty? end Poll It uses parentheses in the method definition It uses the return keyword It uses string interpolation instead of concatenation It uses if not Nothing! 47 / 61

Arrays Instantiated 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 add elements to the end of an array a = [] a << 1 p a #=> [1] 48 / 61

Iterators There are for... in loops in Ruby, but they are discouraged 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 " 49 / 61

Blocks This is the code between the do and end keywords It is convention to use the do... end keywords when the block spans multiple lines But they should be replaced by { } when the method 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" 50 / 61

Hashes Used 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" 51 / 61

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 be used 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"} 52 / 61

Managing Dependencies 53 / 61

Gems Ruby libraries are called gems The command to install them is gem install gem_name When installed, the gem is installed in the current Ruby version's gem directory To use a gem, pass the name of the gem as a string to the require method at the top of the file (e.g. require pry) 54 / 61

The Bundler Gem Bundler is used to manage dependencies, comes in handy in large projects Install the gem using gem install bundler To use, create Gemfile in the directory & add gems to it Run bundle install or bundle for short to install all gems in the Gemfile 55 / 61

The Pry Gem A very useful gem for debugging gem install pry and add require pry to the top of the file Insert the line binding.pry in a Ruby file When you run the program, Ruby will stop at that line and give you a REPL with all variables in scope binding.pry must be deleted from your homework assignments before submitting because it will cause your tests to fail 56 / 61

The Rubocop Gem Rubocop 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 you want to check 3. Run rubocop 57 / 61

The RSpec Gem RSpec will be used for testing Be sure to run gem install rspec You will learn more about RSpec and writing tests in 2 lectures For now, you will be able to run pre-written tests by running rspec from the Command Line 58 / 61

Homework 1 59 / 61

Homework 1 Released now, due next Thursday at 11:59pm When you get started, you'll want to run gem install bundler and bundle install You can run rspec at any time during development to see how you're doing against the test cases You can run rubocop at any time to see how you're doing on style This means that you don't have to submit every time you want to see your output 60 / 61

Homework 1 You will: Set up everything you need to get started with Ruby Complete 5 methods designed to get you more comfortable with Ruby Submit to GitHub Classroom & view results on Travis CI You will fill out exercises.rb There is a provided file called bin/console.rb that will execute your code You can run ruby bin/console.rb and call all of the methods that you defined in exercises.rb 61 / 61