Iterators
- Iterators make it easier to write code
5.times do puts “hello” end
- Integers/floats: times, unto, down to, step
- Range: each, step
- String: each, each_line, each_byte
- Array: each, each_index, each_with_index
- Hash: each, each_key, each_value, each_pair
Methods
- Values are passed in when they are called, and they are sometimes abbreviated as args
- Operators are also methods in ruby
- Syntactic sugar refers to simplifying the code
- Syntactic vinegar – not so tasty code
- Methods are all lowercase with underscores
Classes
- Classes use camel case (they always start with a capital letter): SomeName
- Classes group the code into discreet, well-categorized areas
- Can define methods inside a class
class Animal def make_noise “Moo!” end end
animal.make_noise returns “Moo!”
- make_noise object is created from the class and then we can tell it to do things
- Objects let us organize code into well-categorized areas
- Allow complex behaviors using simple statements
- Instance: an object created from a class
animal = Animal.new puts animal.make_noice
- Animal.new is an instance which is an object
- .new is a class method
Instance Variables
- Instance variables start with an @ symbol – @variable
- Instance variables are used within the instance of a class
- Allow us to keep track of attributes
- Never have access to instance variables from outside the instant
- We can access methods within instance, so need to use methods to get instance variable
- Setter methods – sets a variable equal to value
- Getter methods – getting that value back
Attribute Methods
- Methods that we put into classes – takes symbols and turns them into methods
- attr_reader
- attr_writer
- attr_accessor (creates a reader and a writer method)
Additional Terms
- Instantiated = creating a new instance
- Class Method – a method that can be called on a class even without an instance of the class
- Class attributes – store values that apply to the class generally stored in a class variable @@variable
- Instance variables are only inside the instance
- Inheritance – inherits the methods and attributes of another class
- Can only inherit from one super class
- Modules are wrappers around classes