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
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
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
Overwriting ` Venkat Subramaniam – svenkat@cs.uh.edu 7 Flavors of parallel assignments Venkat Subramaniam – svenkat@cs.uh.edu 8
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
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
catch and throw… Venkat Subramaniam – svenkat@cs.uh.edu 13
Recommend
More recommend