Skip to content

Instantly share code, notes, and snippets.

@nifl
Created August 30, 2011 18:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nifl/1181656 to your computer and use it in GitHub Desktop.
Save nifl/1181656 to your computer and use it in GitHub Desktop.
Ruby notes

Notes on the Ruby programming language

Documentation

Ruby Docs

Local docs using BASH

ri upcase # documents for upcase method
ri Object#inspect # return human-readable representation of an object.

What is an object?

  • a thing or a model of something.
  • an instance of a class. ie, student of students class.
  • almost everything in ruby.

Variables

Variables are not objects,rather, they keep track and reference objects.

Ruby variables should be written lower case w/ underscores.

Scope determines availability of a variable from classes, methods, and other code structures.

Scope Indicators

Global 		- 	$variable
Class 		- 	@@variable
Instance 	- 	@variable
Local 		- 	variable
Block 		- 	variable

Integers

Integers are basic numbers.

The integer class is divided into two sub-classes:

  • Fixnum
  • Bignum

Operators are: =, +, -, /, *

Exponential operator: ** ie, 4 ** 2 = 16

Operator with assignment: +=, -=, *=, /=

x = 4
x =+ 2 
=> 6

same as

x = x + 2

Order of operation: (1 + 2) * 3 = 9

Floats

Floats are decimals or numbers of precision.

specify float class by adding .0 to number

10.0 = Float
10 = Fixnum (integer)
  • Integers are rounded in ruby.
  • Specify precision with floats.

Strings

Strings are sequences of characters.

Strings can be enclosed in single quotes or double quotes.

Double quotes evaluate variables in strings and support escape characters eg, \t - tab, \n - line return, etc..

Concatenation:

"hello" + ' ' + "world"

or using variables:

var + ' ' + var2

Multiplication:

"Gabba" * 5 
	returns
		GabbaGabbaGabbaGabbaGabba

Escaping:

'I\'m escaped'	- using single quotes
"I said, \"I'm escaped\""	- escaping a quotation
  • However! ruby supports arbitrary delimiters for string literals.

so - Don't escape strings!

http://rors.org/2008/10/26/don't-escape-in-strings

Arrays

An array is an ordered, integer-indexed collection of objects

Ruby uses zero indexing (index starts at 0)

array = [] same as array = Array.new

Ruby arrays can take different class types

array = ["Maine", 7, 12.3]

a literal array of strings takes shortcut:

array = %w{Maine Michigan California}

append operator: << eg. array << 0, appends 0 to array

Use the method to_a shorthand for "to array". All classes that use the Enumerable module can be turned into arrays with to_a. This is the most common method to return the array and has the benefit of being easy to change.

a=[1,2,3,4,5,6,7,8,9,10] same as shorthand: a=(1..10).to_a.

Array methods:

.inspect - return array as string. exposes structure.

puts array.inspect

.to_s - to string, joins array elements as a string.

.join - can specify the join

array.join(", ") splits elements w/ comma space.

.split - takes delimited list and returns array.

x = "1,2,3,4,5"
y = x.split(',') // specify delimiter to split at
  => ["1", "2", "3", "4", "5"]

.reverse

.sort - doesn't work w/ mixed types

.uniq- returns new array with no duplicate elements

.uniq! - removes duplicate elements in place

.delete_at() - deletes element at position. subsequent elements shift left.

.delete()

array.delete(4) - removes value '4' (not position 4)

.pop - removes last element

Adding arrays:

array + [9 + 10]

Hashes

Hashes are unordered, object-indexed collection of objects (key-value pairs).

  • Use arrays when order matters.
  • Use hashes when the label matters.

Syntax:

Create: hash = {} // new empty hash

person = {'first_name' => "Gernot", 'last_name' => "Bartels" }

Retrieve values:

look up by key, return value:

person['last_name']
  => "Buck"

reverse retrieval, look up by value, return index:

person.index('Fig')
  => "first_name"

Add key-value pair to existing hash:

person['gender'] = 'male'

Symbols

Symbols are labels used to identify a piece of data and pass messages around different parts of a program.

  • stored in memory once.
  • can be used effectively as labels in hashes.
  • better to use symbols than strings in hashes because strings are unique objects.

Syntax:

prepend colon (:) to the string :dude

Symbols in hashes:

hash = {':first_name' => "Fig", ':last_name' => "Buck" }

Booleans

Comparison and logical operators:

Equal	==
LT		<
GT 		>
LT/EQ	<=
GT/EQ	>=
NOT		!	can be put in front of many things including variables
NOT EQ	!=
AND		&&
OR		||

True and false are objects of the TrueClass and FalseClass.

Complex expressions are evaluated from left to right until condition returns true.

Testing booleans:

x.nil? // check if var is nil, returns 'Local Variable Undefined' if var doesn't exist.
z = 3
z.between?(1,4)
  => true
```ruby

Arrays:
```ruby
[1,2,3].empty?
  => false
[1,2,3].include?(2)
  => true

Hashes:

hash.has_key?
hash.has_value?

Ranges

Inclusive range - 1..10 (includes 10)

Exclusive range - 1...10 (excludes 10)

x = 1..10 // create inclusive range object
  => 1,2,3,4,5,6,7,8,9,10

Range methods:

x.first 
  => 1
x.last
  => 10

These methods are similar to .begin and .end, however, an exclusive range will return an extra value on the .end method. For example, and exclusive range object would return 9 on with the .last method and return 10 using the .end method.

Expand a range and assign to array:

> x = [*x] // asterisk called "splat" operator

Strings can also be ranges (alphabetical)

Constants

Constants are similar to variables

  • constants are not true objects
  • constants point to objects

Variables can change over time, constants do not change.

Constants are named using CAPS (anything that starts with a capital letter considered a constant).

Constant can be overwritten but will return a warning. This is a Ruby idiosyncrasy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment