Augusto Kato

Posted on

# Basic Data Types

Ruby has four basic data types: numbers (integers and floats), strings, symbols and Booleans (true, false and nil).

# Numbers

``````# Addition
1 + 1   #=> 2

# Subtraction
2 - 1   #=> 1

# Multiplication
2 * 2   #=> 4

# Division
10 / 5  #=> 2

# Exponent
2 ** 2  #=> 4
3 ** 4  #=> 81

# Modulus (find the remainder of division)
8 % 2   #=> 0  (8 / 2 = 4; no remainder)
10 % 4  #=> 2  (10 / 4 = 2 with a remainder of 2)
``````

There are two types of numbers in Ruby, integers and floats. Integers represent a whole number, and floats are numbers with a decimal point.
When doing arithmetic with integers, the result will always be a integer.

``````17 / 5    #=> 3, not 3.4
``````

To convert the result, simply replace one of the integers on the expression with a float.

``````17 / 5.0  #=> 3.4
``````

#### Converting Number Types

``````# To convert an integer to a float:
13.to_f   #=> 13.0

# To convert a float to an integer:
13.0.to_i #=> 13
13.9.to_i #=> 13
``````

#### Useful Number Methods

#even?

``````8.even? #=> true
5.even? #=> false
``````

#odd?

``````4.odd? #=> false
9.odd? #=> true
``````

# Strings

#### Concatenation

``````# With the plus operator:
"Hello " + "beautiful " + "World!"    #=> "Hello beautiful World!"

# With the shovel operator:
"Hello " << "beautiful " << "World!"  #=> "Hello beautiful World!"

# With the concat method:
"Hello ".concat("beautiful ").concat("World!")  #=> "Hello beautiful World!"
``````

#### Substrings

``````"hello"[0]      #=> "h"

"hello"[0..1]   #=> "he"

"hello"[0, 4]   #=> "hell"

"hello"[-1]     #=> "o"
``````

#### Escape characters

``````\\  #=> Need a backslash in your string?
\b  #=> Backspace
\r  #=> Carriage return, for those of you that love typewriters
\n  #=> Newline. You'll likely use this one the most.
\s  #=> Space
\t  #=> Tab
\"  #=> Double quotation mark
\'  #=> Single quotation mark
``````
``````irb(main):001:0> puts "Hello \n\nHello"
Hello

Hello
=> nil
``````

#### Interpolation

Evaluate a string that contains placeholder variables. Use double quotes so that string interpolation will work!

``````name = "harukat"

puts "Hello, #{name}" #=> "Hello, harukat"
puts 'Hello, #{name}' #=> "Hello, #{name}"
``````

#### Common String Methods

#capitalize

``````"hello".capitalize #=> "Hello"
``````

#include?

``````"hello".include?("lo")  #=> true

"hello".include?("z")   #=> false
``````

#upcase

``````"hello".upcase  #=> "HELLO"
``````

#downcase

``````"Hello".downcase  #=> "hello"
``````

#empty?

``````"hello".empty?  #=> false

"".empty?       #=> true
``````

#length

``````"hello".length  #=> 5
``````

#reverse

``````"hello".reverse  #=> "olleh"
``````

#split

``````"hello world".split  #=> ["hello", "world"]

"hello".split("")    #=> ["h", "e", "l", "l", "o"]
``````

#strip

``````" hello, world   ".strip  #=> "hello, world"
``````

#### More examples

``````"he77o".sub("7", "l")           #=> "hel7o"

"he77o".gsub("7", "l")          #=> "hello"

"hello".insert(-1, " dude")     #=> "hello dude"

"hello world".delete("l")       #=> "heo word"

"!".prepend("hello, ", "world") #=> "hello, world!"
``````

#### Converting other objects to strings

Using the `to_s` method, you can convert pretty much anything to a string. Here are some examples:

``````2.to_s        #=> "2"

nil.to_s      #=> ""

:symbol.to_s  #=> "symbol"
``````

# Symbols

#### Create a Symbol

To create a symbol, simply put a colon at the beginning of some text:

``````:my_symbol
``````

# Booleans

#### True and False

`true` represents something that is true, and `false` represents something that is false.

#### Nil

`nil` represents “nothing”. Everything in Ruby has a return value. When a piece of code doesn’t have anything to return, it will return `nil`.

# Basic Data Structures

#### Arrays

An array is used to organize information into an ordered list. In Ruby, an array literal is denoted by square brackets `[ ]`.

``````irb :001 > [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
``````

#### Hashes

hash, sometimes referred to as a dictionary, is a set of key-value pairs. Hash literals are represented with curly braces `{ }`. A key-value pair is an association where a key is assigned a specific value. A hash consists of a key, usually represented by a symbol, that points to a value (denoted using a `=>`) of any type of data.

``````irb :001 > {:dog => 'barks'}
=> {:dog => 'barks'}
``````

# Variables

#### How to Name Variables

Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live.

``````# bad
a = 19
string = "John"

# good
age = 19
name = "John"
can_swim = false
``````

## Getting Data from a User

One way to get information from the user is to call the `gets` method. `gets` stands for "get string".

``````irb :001 > name = gets
Bob
=> "Bob\n"
``````

The `\n` at the end is the "newline" character and represents the enter key. We'll use `chomp` chained to `gets` to get rid of that.

``````irb :001 > name = gets.chomp
Bob
=> "Bob"
``````

## Variable Scope

### Variable Scope and Blocks

Inner scope can access variables initialized in an outer scope, but not vice versa.

``````# scope.rb
a = 5 # variable is initialized in the outer scope
3.times do |n| # method invocation with a block
a = 3 # is a accessible here, in an inner scope?
end

puts a
``````

## Types of Variables

Constant:

``````MY_CONSTANT = 'I am available throughout your app.'
``````

Global variable:

``````\$var = 'I am also available throughout your app.'
``````

Class variable:

``````@@instances = 0
``````

Instance variable:

``````@var = 'I am available throughout the current instance of this class.'
``````

Local variable:

``````var = 'I must be passed around to cross scope boundaries.'
``````