Ruby Cheatsheet - Jesus Castello Flashcards
Strings
A string is a sequence of characters inside two quotation marks (“”). Used to represent text & data. Also can use single quotation marks (‘’).
Important methods for Strings
- size
- empty?
- include?
- gsub
- split
Hashes
A hash ( {} ) is a key-value pair ( a => b) data structure. Used as a dictionary. You can access hash elements by their keys. Keys are unique.
Important methods for hashes
- key?
- fetch
- new (for default value)
- merge
Hash example
#Create h = { a: 1, b: 2, c: 3 } #Access h[:a] # Set h[:test] = 10
Symbol
A static string used for identification, one common example is hash keys. They always start with a colon ( :bacon). Symbols are never used for their content (the individual characters).
nil
A singleton class (only one object allowed) that represents a default or “not found” kind of value.
Evaluates to “false” in a conditional context.
Array
An object used to represent a list of objects. An array can contain any kind of object ( a = [1, “abc”, []] ), including other arrays.
You access array elements with their index ( a[0] ) & nested arrays with a[0][0] .
Important methods for Array
- size
- empty?
- push / pop
- join
- flatten
Enumerable
A Ruby module used to iterate over the elements of any class that implements the each method, like Array, Range & Hash.
Important methods for Enumerable
- map
- select
- inject
Method count
exactly what the name says, count things that evaluate to true inside a block
method map
Transforms every element of the enumerable object and returns the new version as an array
FILE
A class that helps you work with files in Ruby. Anything from reading them, writing to them or even getting info about them, like the file size.