Methods & Expressions Venkat Subramaniam svenkat@cs.uh.edu 1 - - PDF document

methods expressions
SMART_READER_LITE
LIVE PREVIEW

Methods & Expressions Venkat Subramaniam svenkat@cs.uh.edu 1 - - PDF document

Methods & Expressions Venkat Subramaniam svenkat@cs.uh.edu 1 Methods Take list of arguments May be suffixed with ?, = , or ! discussed earlier Arguments may take default values An argument with * indicates


slide-1
SLIDE 1

1

Venkat Subramaniam – svenkat@cs.uh.edu

Methods & Expressions

2

Venkat Subramaniam – svenkat@cs.uh.edu

Methods

  • Take list of arguments
  • May be suffixed with ?, = , or !

– discussed earlier

  • Arguments may take default values
  • An argument with * indicates variable

number of arguments

– Name represents an array of trailing arguments

  • An argument with a & indicates a block

– see closure session for example

slide-2
SLIDE 2

3

Venkat Subramaniam – svenkat@cs.uh.edu

Methods…

4

Venkat Subramaniam – svenkat@cs.uh.edu

Expressions

  • Very powerful
  • Almost anything in Ruby returns value

– including if

slide-3
SLIDE 3

5

Venkat Subramaniam – svenkat@cs.uh.edu

Operators

  • Operators are defined as methods

6

Venkat Subramaniam – svenkat@cs.uh.edu

Commands

  • backquotes ` (by default) or % x { } are

used for underlying OS commands

  • $? has exit status
  • ` goes to Kernel.` method
slide-4
SLIDE 4

7

Venkat Subramaniam – svenkat@cs.uh.edu

Overwriting `

8

Venkat Subramaniam – svenkat@cs.uh.edu

Flavors of parallel assignments

slide-5
SLIDE 5

9

Venkat Subramaniam – svenkat@cs.uh.edu

Exceptions

  • Exception handling features from other OO

languages can be seen here

– Yes, with some interesting Rubyisms

  • Create your own exception class if you like

– Inherit from StandardError

  • begin – end – rescue
  • ensure clause is like finally in Java/ .NET
  • else clause may be used to execute code if no

exception is thrown

  • retry allows you to repeat code from beginning
  • raise is used to throw exception
  • Global $! has exception object

– Or you can assign it to a friendly name using = >

10

Venkat Subramaniam – svenkat@cs.uh.edu

Exception…

slide-6
SLIDE 6

11

Venkat Subramaniam – svenkat@cs.uh.edu

raise

  • raise

– rethrows a rescued exception

  • raise “message”

– throws a RuntimeError with message

  • raise TYPE, “message”, caller

– raises exception of mentioned type with given message and stack details reported by the Kernel’s caller method

12

Venkat Subramaniam – svenkat@cs.uh.edu

catch and throw

  • Allows you to set a method in code to

which jump back to from a throw

  • Helps to write code which allows you to

bounce back to some stack level if something happens

  • Not quite exception handling, but may

come in handy at times

slide-7
SLIDE 7

13

Venkat Subramaniam – svenkat@cs.uh.edu

catch and throw…