Ruby Language Overview handout #7 Summary of Ruby features numbers: Integer (3, 802), Float (3.4) booleans: true, false strings: "hello", "how are you?" arrays: [3, 15, "hello", [7, "howdy"], 308.4, true] ranges: 1..10, 'a'..'z' hash: {"stuart"=>"reges", "joe"=>"biden", "donald"=>"trump"} class Foo [< <superclass>] <definitions> end def f(p1, p2, ..., pn) <body> end def f(p1 = v1, p2 = v2, ..., pn = vn) <body> end Syntactic sugar for defining getters and setters: attr_reader symbol1, symbol2, ..., symbol-n attr_writer symbol1, symbol2, ..., symbol-n The constructor for a class always calls a method called initialize. public/protected/private keywords used inside a class to mean "starting here, constructs have this kind of access" instance-variables start with @ class-variables (static variables) start with @@ symbols start with : if <bool-expr> [then] <body> elsif <bool-expr> [then] <body> else <body> end while <bool-expr> [do] <body> end for <variable> in <collection> [do] <body> end loop do <statements> break if <bool-expr> <statements> end <variable>.<method>(<params>) { <block> } <variable>.<method>(<params>) do <block> end <block> can begin with |params| and has a sequence of statements embed an expression to be evaluated in a string: "text before #{expression to evaluate} text after" a method takes a block if it includes calls on yield nil is a special value that represents "no object" Useful methods arithmetic: +, -, *, /, %, ** (exponentiation), +=, -=, *= mathematical: Math.sqrt, Math.sin, Math.cos relational: <, >, <=, >=, !=, == logical: &&, ||, ! conversion: <Integer>.to_f, <Float>.to_i, <Float>.round, <Object>.to_s random: rand, rand(<integer>) higher-order: map, filter, find, find_all, any?, all?, inject, reduce Array/String: x.length # of elements (also Hash) x[i] element i (0-based indexing, also Hash) x[i, n] slice with n elements starting at i x[i..j] slice with values at index i through j x << v append v to x x.sort sort values x.member? v does it contain v? x.index v index of v in x push v appends v to end of array (Arrays only) pop remove and return top value (Arrays only) chomp eliminate trailing newline from string (String only) upcase uppercase version of string (String only) Input/Output puts x like Java println print x like Java print (stay on current output line) print x, y print multiple values gets reads a line of input File.open(s) returns a file object for given file <file>.gets read a line from file object
Stuart Reges
Last modified: Mon Feb 24 09:07:26 PST 2025