methods expressions
play

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


  1. 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 variable number of arguments – Name represents an array of trailing arguments • An argument with a & indicates a block – see closure session for example Venkat Subramaniam – svenkat@cs.uh.edu 2

  2. Methods… Venkat Subramaniam – svenkat@cs.uh.edu 3 Expressions • Very powerful • Almost anything in Ruby returns value – including if Venkat Subramaniam – svenkat@cs.uh.edu 4

  3. Operators • Operators are defined as methods Venkat Subramaniam – svenkat@cs.uh.edu 5 Commands • backquotes ` (by default) or % x { } are used for underlying OS commands • $? has exit status • ` goes to Kernel.` method Venkat Subramaniam – svenkat@cs.uh.edu 6

  4. Overwriting ` Venkat Subramaniam – svenkat@cs.uh.edu 7 Flavors of parallel assignments Venkat Subramaniam – svenkat@cs.uh.edu 8

  5. 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 = > Venkat Subramaniam – svenkat@cs.uh.edu 9 Exception… Venkat Subramaniam – svenkat@cs.uh.edu 10

  6. 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 Venkat Subramaniam – svenkat@cs.uh.edu 11 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 Venkat Subramaniam – svenkat@cs.uh.edu 12

  7. catch and throw… Venkat Subramaniam – svenkat@cs.uh.edu 13

Recommend


More recommend