Ruby
I started working through and familiarising myself with Ruby and going through basic programming concepts explained below.
IRB
IRB is an interactive Ruby shell and it is a tool to interactively execute Ruby expressions which is read from the input and see the result directly. It is a REPL so will read, evaluate, print and loop. Writing 'irb' on the terminal will open up the shell, 'exit' will terminate the shell and return to your system shell.
Strings
A string is an object which represents a number of characters.
Create a new string
string = 'This is a string'
string = "This is also a string"
A string can be created by using single or double quotation marks ("") or (''). However, we can only use double quotation marks for any string interpolation.
Combine strings
str = 'Hello, '
str + 'how are you?'
# 'Hello, how are you?'
String methods:
.concat
- merges strings.upcase
- capitalises the string.chars
- returns an array of characters in the string.gsub
- returns a copy of the string which is substituted with the second argument
Variables
You can define a variable by assigning values using the = operator. The name on the left is the name of the variable you wish to name, the right side of the assignment is the value attached to the left variable name. You can also change the variable by naming the same variable and then assigning a new value.
person_one = 'katie'
person_one = 'sarah'
We can use variables to store different types of values such as numeric values, characters, strings or memory addresses. Variables hold objects and refer to a specific object located in computer memory.
There are 5 different types of variables:
- Global variables
($apple)
- Instance variables
(@apple)
- Class variable
(@@apple)
- Constant
(APPLE)
Booleans
Boolean refers to either 'truth' or 'false'.
Everything in Ruby is truthy except from false
and nil
which are falsy.
Even an empty string is truthy as the string is an instance of the String class.
Comparison Operators
Comparison operators take values (numbers or strings) as arguments and are used to check for equality between two values. Ruby provides following comparison operators:
==
: equal!=
: not equal>
: greater than<
: less than>=
: greater than or equal to<=
: less than or equal to<=>
: combined comparison operator===
: test equality
Control Flows
Control flows are statements that will control the flow of a program.
if/else statement
number = 0
if number.positive?
return true
elsif number.negative?
return false
else
return 0
end
# true
switch statement
case:
Starts a case statement definition. Takes the variable you are going to work with.
when:
Every condition that can be matched is one when statement.
else:
If nothing matches then do this. Optional.
case capacity
when 0
"You ran out of gas."
when 1..20
"The tank is almost empty. Quickly, find a gas station!"
when 21..70
"You should be ok for now."
when 71..100
"The tank is almost full."
else
"Error: capacity has an invalid value (#{capacity})"
while statement
The while statement that allows code to be executed repeatedly based on a given boolean condition. It executes the code while the condition is true.
The while keyword executes the statements inside the block enclosed by the end keyword. The statements are executed each time the expression is evaluated to true.
i = 0
sum = 0
while i < 10 do
i = i + 1
sum = sum + i
end
puts "The sum of 0..9 values is #{sum}"
We calculate the sum of values from a range of numbers.
The while loop has three parts: initialization, testing and updating. Each execution of the statement is called a cycle.
Initialisation
i = 0
sum = 0
We initiate the i and the sum variables. The i is used as a counter.
Testing
while i < 10 do
...
end
The do keyword is optional. The statements in the body are executed until the expression is evaluated to false.
Updating
i = i + 1
This is the last phase of the while loop. We increment the counter.
The sum of 0..9 values is 55
until statement
The until statement executes code while the condition is false. The loop stops when the condition is true.
hours_left = 12
until hours_left == 0
if hours_left == 1
puts "There is #{hours_left} hour left"
else
puts "There are #{hours_left} hours left"
end
hours_left -= 1
end
We have a variable hours_left. We begin a count down. In each loop cycle, we print how many hours are left there. When the variable equals zero, the loop is stopped.
Break keyword
We can use the break keyword to break out of the loop on while, for and case statements
for number in 0..10
if number > 5 then
break
end
puts "The number is #{number}"
end
The for in statement will loop through the numbers from 0 - 10. If the number will be more than the 10 the loop will be halted. Prints each number once gone through the loop. We have used an if condition which is checking if the number is greater than 5, then it will break the statement and the loop will be halted, then prints "The number is 5"
Objects
We can create new objects by sending the message new
to the class.
For instance when we type in an integer we are basically creating a new instance from the integer class sending it the message new. Ruby automatically does this under the hood.
1 = Integer.new
# 1
2 = Integer.new
# 2
return value from new
#` is a hexadecimal number returned from Person.new
We have told Person class to create a new instance, that class returns to us the instance it just created. It is a memory address that the programs uses to remember where objects are located on the computer.
Similarities between classes and instances:
- Both objects
- Both exist in the program world -Both have memory address
Differences between classes and instances:
- Class objects produce Instance objects
- Instance objects do all different sorts of things
- Operators and Comparison Operators
Bring on week 2!