Ruby Data Types
Ruby is a dynamically typed language, meaning you don't need to declare variable types. Let's explore the fundamental data types you'll use in Rails.
Strings
Strings are sequences of characters. Ruby offers several ways to create them:
ruby
1# Single quotes (literal)
2name = 'John Doe'
3
4# Double quotes (allows interpolation and escape characters)
5greeting = "Hello, #{name}!" # => "Hello, John Doe!"
6
7# Multi-line strings
8description = <<~TEXT
9 This is a multi-line string.
10 It preserves line breaks.
11 Very useful for long text.
12TEXT
13
14# Common string methods
15name = " Ruby on Rails "
16
17name.length # => 17
18name.upcase # => " RUBY ON RAILS "
19name.downcase # => " ruby on rails "
20name.capitalize # => " ruby on rails "
21name.strip # => "Ruby on Rails"
22name.split(" ") # => ["Ruby", "on", "Rails"]
23name.include?("Ruby") # => true
24name.gsub("Rails", "Framework") # => " Ruby on Framework "String Interpolation
ruby
1user = "Alice"
2age = 25
3
4# Using interpolation (double quotes required)
5message = "#{user} is #{age} years old"
6# => "Alice is 25 years old"
7
8# You can include any Ruby expression
9price = 19.99
10puts "Total: $#{'%.2f' % (price * 1.1)}"
11# => "Total: $21.99"Numbers
Ruby has two main number types: Integers and Floats.
ruby
1# Integers
2count = 42
3negative = -17
4big_number = 1_000_000 # Underscores for readability
5
6# Floats (decimal numbers)
7price = 19.99
8pi = 3.14159
9
10# Arithmetic operations
1110 + 3 # => 13 (addition)
1210 - 3 # => 7 (subtraction)
1310 * 3 # => 30 (multiplication)
1410 / 3 # => 3 (integer division)
1510.0 / 3 # => 3.333... (float division)
1610 % 3 # => 1 (modulo/remainder)
1710 ** 3 # => 1000 (exponentiation)
18
19# Useful methods
20-5.abs # => 5
213.14.round # => 3
223.14.ceil # => 4
233.14.floor # => 3
245.even? # => false
255.odd? # => true
2610.between?(5, 15) # => trueBooleans
Booleans represent true or false values:
ruby
1is_active = true
2is_deleted = false
3
4# In Ruby, only nil and false are falsy
5# Everything else is truthy (including 0 and empty strings)
6
7if 0
8 puts "0 is truthy in Ruby!"
9end
10
11# Comparison operators
125 == 5 # => true (equality)
135 != 3 # => true (not equal)
145 > 3 # => true (greater than)
155 < 3 # => false (less than)
165 >= 5 # => true (greater or equal)
175 <= 5 # => true (less or equal)
18
19# Logical operators
20true && false # => false (and)
21true || false # => true (or)
22!true # => false (not)Symbols
Symbols are immutable, reusable identifiers. They're more memory-efficient than strings:
ruby
1# Symbols start with a colon
2status = :active
3role = :admin
4
5# Symbols are commonly used as hash keys
6user = {
7 name: "John", # Same as :name => "John"
8 email: "john@example.com",
9 role: :admin
10}
11
12# Comparing symbols is faster than strings
13:active == :active # => true (comparing object IDs)
14"active" == "active" # => true (comparing characters)
15
16# Converting between symbols and strings
17:hello.to_s # => "hello"
18"hello".to_sym # => :helloArrays
Arrays are ordered collections that can hold any type of object:
ruby
1# Creating arrays
2numbers = [1, 2, 3, 4, 5]
3names = ["Alice", "Bob", "Charlie"]
4mixed = [1, "two", :three, 4.0]
5
6# Shorthand for string arrays
7fruits = %w[apple banana cherry] # => ["apple", "banana", "cherry"]
8
9# Accessing elements
10numbers[0] # => 1 (first element)
11numbers[-1] # => 5 (last element)
12numbers[1..3] # => [2, 3, 4] (range)
13numbers.first # => 1
14numbers.last # => 5
15
16# Modifying arrays
17numbers << 6 # Add to end: [1, 2, 3, 4, 5, 6]
18numbers.push(7) # Same: [1, 2, 3, 4, 5, 6, 7]
19numbers.unshift(0) # Add to front: [0, 1, 2, 3, 4, 5, 6, 7]
20numbers.pop # Remove last: returns 7
21numbers.shift # Remove first: returns 0
22
23# Useful array methods
24[1, 2, 3].length # => 3
25[1, 2, 3].empty? # => false
26[1, 2, 2, 3].uniq # => [1, 2, 3]
27[3, 1, 2].sort # => [1, 2, 3]
28[1, 2, 3].reverse # => [3, 2, 1]
29[1, 2, 3].include?(2) # => true
30[1, 2, 3].join(", ") # => "1, 2, 3"Hashes
Hashes are key-value collections (like dictionaries in other languages):
ruby
1# Creating hashes
2user = {
3 name: "John",
4 age: 30,
5 email: "john@example.com"
6}
7
8# Old syntax (still valid)
9user = { :name => "John", :age => 30 }
10
11# Accessing values
12user[:name] # => "John"
13user[:age] # => 30
14user[:missing] # => nil
15
16# With default value
17scores = Hash.new(0)
18scores[:player1] += 10 # Works without error
19
20# Modifying hashes
21user[:city] = "New York" # Add new key
22user[:age] = 31 # Update existing key
23user.delete(:email) # Remove a key
24
25# Useful hash methods
26user.keys # => [:name, :age, :city]
27user.values # => ["John", 31, "New York"]
28user.key?(:name) # => true
29user.value?("John") # => true
30user.merge({ country: "USA" }) # Combine hashesNil
nil represents the absence of a value:
ruby
1value = nil
2
3# Checking for nil
4value.nil? # => true
5value == nil # => true (but .nil? is preferred)
6
7# Safe navigation operator (Ruby 2.3+)
8user = nil
9user&.name # => nil (no error)
10
11# Default values
12name = nil
13name || "Anonymous" # => "Anonymous"
14
15# Dig method for nested hashes
16data = { user: { profile: { name: "John" } } }
17data.dig(:user, :profile, :name) # => "John"
18data.dig(:user, :settings, :theme) # => nil (no error)Type Conversion
Ruby provides methods to convert between types:
ruby
1# To String
242.to_s # => "42"
33.14.to_s # => "3.14"
4:symbol.to_s # => "symbol"
5[1, 2, 3].to_s # => "[1, 2, 3]"
6
7# To Integer
8"42".to_i # => 42
9"3.14".to_i # => 3
10"hello".to_i # => 0
11
12# To Float
13"3.14".to_f # => 3.14
1442.to_f # => 42.0
15
16# To Symbol
17"hello".to_sym # => :hello
18
19# To Array
20(1..5).to_a # => [1, 2, 3, 4, 5]
21{ a: 1 }.to_a # => [[:a, 1]]Understanding these data types is fundamental to working with Ruby and Rails!
