Ruby: Introduction, Basics

Similar documents
Ruby: Introduction, Basics

Ruby: Introduction, Basics

CS 5142 Scripting Languages

Ruby: Objects and Dynamic Types

The PCAT Programming Language Reference Manual

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

G Programming Languages - Fall 2012

Your First Ruby Script

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

FRAC: Language Reference Manual

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Java Bytecode (binary file)

CS 360 Programming Languages Interpreters

CMPT 125: Lecture 3 Data and Expressions

The SPL Programming Language Reference Manual

Expressions & Assignment Statements

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341

Basics of Java Programming

Chapter 7. Expressions and Assignment Statements (updated edition 11) ISBN

Program Fundamentals

CSE 341, Autumn 2015, Ruby Introduction Summary

ENGR 101 Engineering Design Workshop

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Language Reference Manual

SPARK-PL: Introduction

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

Full file at

Chapter 7. Expressions and Assignment Statements ISBN

System Software. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 13

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

The Warhol Language Reference Manual

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Lecture 3. More About C

Chapter 7. Expressions and Assignment Statements ISBN

Software II: Principles of Programming Languages. Why Expressions?

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

Chapter 7. Expressions and Assignment Statements

Typescript on LLVM Language Reference Manual

Computational Expression

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

Chapter 7. Expressions and Assignment Statements

Chapter 1. Fundamentals of Higher Order Programming

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

CSC Web Programming. Introduction to JavaScript

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

PYTHON- AN INNOVATION

15.1 Origins and Uses of Ruby

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Organization of Programming Languages CS3200/5200N. Lecture 11

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

DaMPL. Language Reference Manual. Henrique Grando

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Regular Expressions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 9

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

4. Inputting data or messages to a function is called passing data to the function.

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

NOTE: Answer ANY FOUR of the following 6 sections:

Coral Programming Language Reference Manual

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Expressions and Assignment Statements

Java Primer 1: Types, Classes and Operators

Declaration and Memory

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Lexical Considerations

CHIL CSS HTML Integrated Language

Computer System and programming in C

CGS 3066: Spring 2015 JavaScript Reference

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

CSCE 120: Learning To Code

Documentation for LISP in BASIC

Lexical Considerations

Decaf Language Reference

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Overview of the Ruby Language. By Ron Haley

CS 231 Data Structures and Algorithms, Fall 2016

Visual C# Instructor s Manual Table of Contents

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

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Scala : an LLVM-targeted Scala compiler

Angela Z: A Language that facilitate the Matrix wise operations Language Reference Manual

Scheme Quick Reference

1 Lexical Considerations

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CPS122 Lecture: From Python to Java

Algorithms and Programming I. Lecture#12 Spring 2015

Chapter 17. Fundamental Concepts Expressed in JavaScript

B The SLLGEN Parsing System

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

JavaScript. Training Offer for JavaScript Introduction JavaScript. JavaScript Objects

Computer Components. Software{ User Programs. Operating System. Hardware

QUIZ: What value is stored in a after this

Lecture 3 Tao Wang 1

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

Variables, Constants, and Data Types

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Transcription:

Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4

Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie objects) Inheritance Strongly typed Classes determine valid operations Some familiar operators Arithmetic, bitwise, comparison, logical Some familiar keywords if, then, else, while, for, class, new

But Ruby Looks Different Punctuation Omits ;'s and often ()'s on function calls Includes function names ending in? and! New keywords and operators def, do..end, yield, unless ** (exp), =~ (match), <=> (spaceship) Rich core libraries Collections: Hashes, Arrays Strings and regular expressions Enumerators for iteration

Deeper Differences As Well Interpreted (typically) Run a program directly, without compiling Dynamically typed Objects have types, variables don't Everything is an object C.f. primitives in Java Code can be passed in to a function as a parameter Added to Java in version 8 ("lambdas")

Compiling Programs Program = Text file Contains easy-to-understand statements like "print", "if", "while", etc. But a computer can only execute machine instructions Instruction set architecture of the CPU A compiler translates the program (source code) into an executable (machine code) Recall "Bugs World" from CSE 2231 Examples: C, C++, Objective-C, Ada

Interpreting Programs An interpreter reads a program and executes it directly Advantages Platform independence Read-eval-print loop (aka REPL) Reflection Disadvantages Speed Later error detection (i.e., at run time) Examples: JavaScript, Python, Ruby

Combination of Both A language is not inherently compiled or interpreted A property of its implementation Sometimes a combination is used: Compile source code into an intermediate representation (byte code) Interpret the byte code Examples of combination: Java, C#

Ruby is (Usually) Interpretted REPL with Ruby interpreter, irb $ irb >> 3 + 4 => 7 >> puts "hello world" hello world => nil >> def square(x) x**2 end => :square >> square -4 => 16

Literals Numbers (FixNum, Float, Rational, Complex) 83, 0123, 0x53, 0b1010011, 0b101_0011 123.45, 1.2345e2, 12345E-2 2/3r, 4+3i Strings Delimeters " " and ' ' Interpolation of #{ } occurs (only) inside " " "Sum 6+3 is #{6+3}" is "Sum 6+3 is 9" Custom delimeter with %Q or %q Ranges 0..4 includes start and end value (0,1,2,3,4) "cab"..."cat" does not include end value Arrays and hashes (later)

Comments and Statements Single-line comments start with # Don't confuse it with string interpolation! Multi-line comments bracketed by =begin =end Must appear at beginning of line All statements have a value result Convention: => to indicate result "Hi #{name}" + "!" #=> "Hi Liam!"

Operators Arithmetic: + - * / % ** / is either or div, depending on operands Integer / (div) rounds towards -, not 0 % is modulus, not remainder 1 / 3.0 #=> 0.3333333333333333 1 / 3 #=> 0 (same as Java) -1 / 3 #=> -1 (not 0 as in Java) -1 % 3 #=> 2 (not -1 as in Java) Bitwise: ~ & ^ << >> 5 2 #=> 7 (ie 0b101 0b10) 13 ^ 6 #=> 11 (ie 0b1101 ^ 0b0110) 5 << 2 #=> 20 (ie 0b101 << 2)

Operators (Continued) Comparison: < > <= >= <=> Last is so-called "spaceship operator" Returns -1/0/1 iff LHS is smaller/equal/larger than RHS "cab" <=> "da" #=> -1 "cab" <=> "ba" #=> 1 Logical: &&! and or not Words have low precedence (below =) "do_this or die" idiom needs low-binding x = crazy or raise "problem"

Pseudo Variables Objects self, the receiver of the current method (recall this) nil, nothingness (recall null) Booleans true, false nil also evaluates to false 0 is not false, it is true just like 1 or -4! Specials FILE, the current source file name LINE, the current line number

Significance in Names A variable's name affects semantics! Variable name determines its scope Local: start with lowercase letter (or _) Global: start with $ Many pre-defined global variables exist, e.g.: $/ is the input record separator (newline) $; is the default field separator (space) Instance: start with @ Class: start with @@ Variable name determines mutability Constant: start with uppercase (Size) but idiom is all upper case (SIZE)

Basic Statements: Conditionals Classic structure if (boolean_condition) [then]... else... end But usually omit ( )'s and "then" keyword if x < 10 puts "small" end "If" keyword also a statement modifier x = x + 1 if x < LIMIT Good for single-line body Good when statement execution is common case Good for positive conditions

Variations on Conditionals Unless: equivalent to "if not " unless size >= 10 puts "small" end Can also be a statement modifier x = x + 1 unless x >= LIMIT Same idiom: single-line body, execution is common case, and positive condition Do not use "else" with "unless" Do not use negation in condition Do not use else with statement modifiers

Pitfalls with Conditionals Keyword "elsif" instead of "else if" if x < 10 puts "small" elsif x < 20 puts "medium" else puts "large" end If's do not create nested lexical scope if x < 10 y = x end puts y #y is defined, but could be nil puts z #NameError: undefined local var z

Case Statements are General [variable = ] case expression when nil statements execute if the expr was nil when value # e.g. 0, 'start' statements execute if expr equals value when type # e.g. String statements execute if expr resulted in Type when /regexp/ # e.g. /[aeiou]/ statements execute if expr matches regexp when min..max statements execute if the expr is in range else statements end

Basic Iteration: While and Until Classic structure while boolean_condition [do] end Can also be used as a statement modifier work while awake Until: equivalent to "while not " until i > count end Can also be a used as a statement modifier Pitfall: Modified block executes at least once sleep while dark #may not sleep at all begin i = i + 1 end while i < MAX #always increments i at least once

Functions Definition: keyword def def foo(x, y) x + y #last statement to execute end Value of last statement implicitly returned Convention: Omit explicit return statement Calling functions: ( )'s often omitted foo 13, 4 Idiom: include ( )'s only when chaining foo(13, 4).equal? value Convention: Omit ( ) s in definition when there are no parameters def launch end # good def launch() end # bad

Summary Ruby is a general-purpose, imperative, object-oriented language Ruby is (usually) interpreted REPL Familiar flow-of-control and syntax Some new constructs (e.g., unless, until) Terse (e.g., optional parentheses, optional semicolons, statement modifiers)