Tech

Ruby Programming Language Notes

General Notes:

“Commands” are also called “functions” and “methods”.

  • Functions do 3 things:
    1. They name pieces of code the way variables name strings and numbers.
    2. They take arguments the way your scripts take ‘ARGV’.
    3. Using steps 1 & 2, they let you make your own “mini-scripts” or “tiny commands”.
    4. *You can create a function by using the word ‘def’ in Ruby.
      1. ‘def’ means ‘define’.
  • Functions (aka Commands aka Methods) To Remember:
    • open –Opens the file
    • close –Closes the file. Like “File –> Save…” in your editor.
    • read –Reads the contents fo the file. You can assign the result to a variable.
    • readline –Reads just one line of a text file.
    • truncate –Empties the file!
    • write(‘stuff’) –Writes “stuff’ to the file.
    • seek (0) –Move the read/write location to the beginning of the file.

def #Defining a method….

More methods:

shove ‘<<‘ shovel–adds an element to the end.

.push ‘array.push()‘ –also adds an element to the end, BUT you can use multiple parameters! Push evaluates to the array.

.pop ‘array.pop()‘ –removes the last element of an array; POP evaluates to the removed element.

.unshift ‘array.unshift‘ –adds an element to the front of an array. UNSHIFT evaluates to the array.

.shift ‘array.shift‘ -removes the first element of an array; SHIFT evaluates to the removed element.

PUSH & POP–operate on the END of an array.

UNSHIFT & SHIFT–operate on the FRONT of an array;

array/string.index(ele) –evaluates to the index where element is found.

array/string.include?(ele) –evaluates to a boolean indicating if element is found.

array/string.reverse –evaluates to a new reverse version of the array or string.

array/string.reverse! –reverses an array/string in place.

array/string.length –returns the number of elements.

Array/String Slicing

array/string [startIdx..endIdx] -grabs elements from starting index to ending index (inclusive of the ending index. Note the two dots between.)

array/string [startIdx…endIdx] -grabs elements from starting index to the ending index (exclusive or excluding the element at endIdx).

Indexing, or word[i], is used to grab single elements of an array or string. But SLICING can grab MULTIPLE elements.

‘Split’ & ‘Join’

string.split -evaluates to an array; thus split can only be used on a string!

array.join -evaluates to a string; thus join can only be used on an array!