Ruby Topic Maps. Introduction to Ruby. Benjamin Bock.

Similar documents
CS 5142 Scripting Languages

Ruby: Introduction, Basics

Ruby: Introduction, Basics

What is Ruby? CSc 372. Comparative Programming Languages. 27 : Ruby Introduction. Department of Computer Science University of Arizona

Ruby. An Introduction

A Tour of Ruby.... for Java programmers

Ruby: Introduction, Basics

Overview of the Ruby Language. By Ron Haley

Beyond Blocks: Python Session #1

Introduction to Ruby, part I

Programming Ruby The Pragmatic Programmers Guide

CEU s (Continuing Education Units) 12 Hours (i.e. Mon Thurs 5 9PM or Sat Sun 8AM 5PM)

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

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Programming Paradigms

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

9.2 Linux Essentials Exam Objectives

Your First Ruby Script

Ruby : A Dynamic Object Oriented Scripting Language

CSE 341, Autumn 2015, Ruby Introduction Summary

15.1 Origins and Uses of Ruby

Ruby on Rails for PHP and Java Developers

Ruby on Rails TKK, Otto Hilska

Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods

A shell can be used in one of two ways:

RUBY QUICK REFERENCE GUIDE

Crash Course in Ruby. Summer Institute 2018

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

CSE 413 Programming Languages & Implementation. Hal Perkins Winter 2019 Ruby Containers, Blocks, and Procs

Conditional Control Structures. Dr.T.Logeswari

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

why you should use Ruby

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

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

Recap: Functions as first-class values

Linux Shell Scripting. Linux System Administration COMP2018 Summer 2017

Reflection and Metaprogramming

Functions & First Class Function Values

CS 11 python track: lecture 4

CHAPTER 3: CORE PROGRAMMING ELEMENTS

Lecture 4. Log into Linux Reminder: Homework 1 due today, 4:30pm Homework 2 out, due next Tuesday Project 1 out, due next Thursday Questions?

Advanced Python. Executive Summary, Session 1

Ruby, with foxes. Ruby, cont d. Warning. why's (poignant) Guide to Ruby

Unit 7. 'while' Loops

Ruby. A Very Brief Introduction. Andreas Klappenecker

Racket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Language Syntax version beta Proposed Syntax

More Scripting and Regular Expressions. Todd Kelley CST8207 Todd Kelley 1

Introduction to Ruby. Part I

Scheme: Strings Scheme: I/O

Ruby assign variable if nil. Ruby assign variable if nil.zip

Installation Download and installation instructions can be found at

bash, part 3 Chris GauthierDickey

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

INTRODUCTION TO RUBY PETER COOPER

Intro to Ruby Scripting

UNIX shell scripting

SCHEME AND CALCULATOR 5b

Shell programming. Introduction to Operating Systems

Principles of Programming Languages 2017W, Functional Programming

Lecture 1. Basic Ruby 1 / 61

Ruby. Mooly Sagiv. Most slides taken from Dan Grossman

(Refer Slide Time: 01:12)

bash Tests and Looping Administrative Shell Scripting COMP2101 Fall 2017

Common LISP Tutorial 1 (Basic)

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

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CS 11 python track: lecture 2

CS 105 Perl: Completing the Toolbox

bash Execution Control COMP2101 Winter 2019

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

L3 Programming September 19, OCaml Cheatsheet

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Project 5 Due 11:59:59pm Wed, July 16, 2014

Ruby QuickRef. Contents: Sitemap Search Zen Spider Website / The Language Freak / Ruby / Ruby QuickRef

Strings and Variables

CS 251 Intermediate Programming Java Basics

Object Model Comparisons

Conditionals and Recursion. Python Part 4

RUBY VARIABLES, CONSTANTS AND LITERALS

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

Classes and Objects in Ruby

A LISP Interpreter in ML

The PCAT Programming Language Reference Manual

At full speed with Python

Array variable in class ruby. Array variable in class ruby.zip

COMS 6100 Class Notes 3

Lecture Transcript While and Do While Statements in C++

CS 390 Software Engineering Lecture 6 Ruby

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Advanced Unix Programming Module 03 Raju Alluri spurthi.com

Late Binding; OOP as a Racket Pattern

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

Writing code that I'm not smart enough to write. A funny thing happened at Lambda Jam

Programming Languages & Compilers. Programming Languages and Compilers (CS 421) Programming Languages & Compilers. Major Phases of a Compiler

CS1 Lecture 3 Jan. 18, 2019

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Inductive Data Types

Programming Languages and Compilers (CS 421)

Transcription:

Ruby Topic Maps http://rtm.rubyforge.org Introduction to Ruby Benjamin Bock 1

Calculator irb(main):001:0> 1+2 Type irb in your Terminal / Command / Shell window to start the interactive Ruby interpreter irb(main):002:0> 3*4 irb(main):003:0> 5**3 irb(main):004:0> Math.sqrt(81) 2

Simple Types # comment until of line "String" 1 # number 1.0 # floating point number 1_000_000_000_000 # BigNum :symbol # use these as keys in Hashes, they are faster than Strings! true, false, self, nil 3

Even More Types a = [1,2,3] # Array a[2] # access array position h = { :key => "value" } # Hash h[:key2] # access value2 hash "string" =~ /regular expression/ (1..10) # exclusive Range (1...10) # inclusive Rage 4

Numbers 123 1_234 123.45 1.2e 3 0xffff (hex) 0b01011 (binary) 0377 (octal)?a # ASCII character?\c a # Control a?\m a # Meta a?\m \C a # Meta Control a 5

Strings 'no interpolation' "#{interpolation}, and backslashes\n" %q(no interpolation) %Q(interpolation and backslashes) %(interpolation and backslashes) `echo command interpretation with interpolation and backslashes` %x(echo command interpretation with interpolation and backslashes) `ls` # returns output of system command ls 6

Methods def hello puts "hello" def salute(who) puts "Hello #{who}" def salute(who="world") puts "Hello #{who.capitalize}" 7

Method Invocation method obj.method Class::method # keyword parametres: one argument for def method(hash_arg): method(key1 => val1, key2 => val2) becomes: method(arg1, arg2, arg3): method(arg1, *[arg2, arg3]) #as ugly as you want it to be: method(arg1, key1 => val1, key2 => val2, *splat_arg) #{ block } # A bit more formal: invocation := [receiver ('::' '.')] name [ parameters ] [ block ] parameters := ( [param]* [, hashlist] [*array] [&aproc] ) block := { blockbody } do blockbody 8

Everything is an Object nil.class true.object_id 2.75.ceil 5.times do # this a preview, details later puts "I like Ruby!" 9

Everybody is valuable #... and everything has a value # often no "return" statements needed def value 5 x = value # x = 5 y = if 1!= 2 # even if has a value "right" else "wrong" # y == "right" 10

But what if... if condition [then] # true block elsif other_condition # not elseif! # second true block else # last chance # also: z = condition? true_value : false_value 11

Can you tell me the truth? # Yes, it's 42 if 0 then "but this is the case" else "this will not happen" # Only false and nil are not true! # That's handy for == nil checks. 12

This is really the case case my_var when "hi", "hello", "hallo", "salut" puts "it was an greeting" when String puts "it was a string..." when (1..100) puts "A number between 0 and 100" when Numeric puts "A number not in the range above" else puts "What did you give me here?" 13

Back to the Question # there are other conditionals return false if you_dont_like_to_answer unless you_are_already_asleep i_will_go_on # this is not a loop! 14

Iteration Iteration Iteration Iteration 5.times { x puts x } ["alice", "bob"].each do name puts "Hello #{name}" list = [6,7,2,82,12] for x in list do puts x 15

go_on until audience.asleep? loop do body {while,until} bool expr [do] body begin body {while,until} bool expr # we have: break, next,redo, retry 16

Blocks (a.k.a. Closures) search_engines = %w[google Yahoo MSN].map do engine "http://www." + engine.downcase + ".com" %w[abcde fghi jkl mn op q].sort_by { w w.size } 17

Object Oriented Constructs $global_variable module SomeThingLikePackageInJava class SameLikeJava < SuperClass @instance_variable @@class_variable def initialize() puts "I am the constructor" def method(param, optional_param="default") "This String is returned, even without return statement" SomeModule::CONSTANT 18

Meaningful Method Names # usage: some_object.valid?class Person class Person def name; @name; def name=(new_name) @name = new_name def valid? return true unless name && name.empty? false class Person # almost the same attr_accessor :name def valid?; name &&! name.empty?; p = Person.new person.valid? person.name = "Benjamin" person.valid? 19

Only one aunt may die # single inheritance only # alternative model: mixins class MyArray include Enumerable def each # your iterator here # Enumerable provides: all? any? collect detect each_with_index entries find find_all grep group_by include? index_by inject map max member? min partition reject select sort sort_by sum to_a to_set zip 20

Ruby is flexible class Numeric def plus(x) self.+(x) y = 5.plus 6 # y is now equal to 11 21

Redefining Methods warn("don't try this at home or at all") class Fixnum def +( other ) self other 5 + 3 # => 2 22

Introspection # Tell me what you are 5.class "qwerty".class # Tell me what you do [1,2,3].methods # this is how I got the list above Enumerable.instance_methods.sort.join(" ") # Would you? Please... some_variable.respond_to? :each 23

Missing Methods # id is the name of the method called, the * syntax collects # all the arguments in an array named 'arguments' def method_missing( id, *arguments ) puts "Method #{id} was called, but not found. It has " + "these arguments: #{arguments.join(", ")}" :a, :b, 10 # => Method was called, but not found. It has these # arguments: a, b, 10 24

eval is evil... class Klass def initialize @secret = 99 k = Klass.new k.instance_eval { @secret } # => 99 # generally: eval("some arbitrary ruby code") 25

...but may be really helpful eval(string [, binding [, filename [,lineno]]]) => obj mod.class_eval(string [, filename [, lineno]]) => obj # there are many blocks like this in the RTM source code module_eval(<< EOS, "( PSEUDO_FILENAME_FOR_TRACES )", 1) def #{method_name_variable} some custom method using #{more} #{variables} EOS 26

Something (not so) exceptional begin # some code # may raise an exception rescue ExceptionType => ex # exception handler else # no exception was raised ensure # this stuff is done for sure raise Exception, "Message" 27

Things we do not cover here alias here docs regex details access restriction predefined variables: $!, $@, $:... backslash constructions: \n \t and some other stuff we do not need today 28

Sources http://www.ruby-lang.org http://www.zenspider.com/languages/ Ruby/QuickRef.html http://www.ruby-doc.org/core/ 29

begin puts "Questions?" x = gets puts response_to(x) until x =~ /(no exit quit)/i puts "Do you need a break?" 30