DEV Community

Augusto Kato
Augusto Kato

Posted on

Basic data types and variables in Ruby

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

17 / 5.0  #=> 3.4
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Useful Number Methods

#even?

8.even? #=> true
5.even? #=> false
Enter fullscreen mode Exit fullscreen mode

#odd?

4.odd? #=> false
9.odd? #=> true
Enter fullscreen mode Exit fullscreen mode

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!"
Enter fullscreen mode Exit fullscreen mode

Substrings

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

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

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

"hello"[-1]     #=> "o"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
irb(main):001:0> puts "Hello \n\nHello"
Hello

Hello
=> nil
Enter fullscreen mode Exit fullscreen mode

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}"
Enter fullscreen mode Exit fullscreen mode

Common String Methods

#capitalize

"hello".capitalize #=> "Hello"
Enter fullscreen mode Exit fullscreen mode

#include?

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

"hello".include?("z")   #=> false
Enter fullscreen mode Exit fullscreen mode

#upcase

"hello".upcase  #=> "HELLO"
Enter fullscreen mode Exit fullscreen mode

#downcase

"Hello".downcase  #=> "hello"
Enter fullscreen mode Exit fullscreen mode

#empty?

"hello".empty?  #=> false

"".empty?       #=> true
Enter fullscreen mode Exit fullscreen mode

#length

"hello".length  #=> 5
Enter fullscreen mode Exit fullscreen mode

#reverse

"hello".reverse  #=> "olleh"
Enter fullscreen mode Exit fullscreen mode

#split

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

"hello".split("")    #=> ["h", "e", "l", "l", "o"]
Enter fullscreen mode Exit fullscreen mode

#strip

" hello, world   ".strip  #=> "hello, world"
Enter fullscreen mode Exit fullscreen mode

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!"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Symbols

Create a Symbol

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

:my_symbol
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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'}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Types of Variables

Constant:

MY_CONSTANT = 'I am available throughout your app.'
Enter fullscreen mode Exit fullscreen mode

Global variable:

$var = 'I am also available throughout your app.'
Enter fullscreen mode Exit fullscreen mode

Class variable:

@@instances = 0
Enter fullscreen mode Exit fullscreen mode

Instance variable:

@var = 'I am available throughout the current instance of this class.'
Enter fullscreen mode Exit fullscreen mode

Local variable:

var = 'I must be passed around to cross scope boundaries.'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)