Variables and Data Types in Ruby
In Ruby, variables are used to store data values. Ruby is dynamically typed, meaning you don't need to declare the type of a variable explicitly.
Declaring Variables
Variables in Ruby are created when you assign a value to them.
age = 25 # Integer
name = "Alice" # String
is_student = true # Boolean
Variable Scope
Ruby has different types of variables based on their scope:
- Local Variables: Start with a lowercase letter or underscore (e.g.,
age
). - Instance Variables: Start with
@
(e.g.,@name
). - Class Variables: Start with
@@
(e.g.,@@count
). - Global Variables: Start with
$
(e.g.,$global
).
Common Data Types
- Integer: Whole numbers (e.g.,
10
,-5
). - Float: Decimal numbers (e.g.,
3.14
,-0.001
). - String: Text data (e.g.,
"Hello"
,'Ruby'
). - Boolean: True or False values.
- Array: Ordered collection of elements (e.g.,
[1, 2, 3]
). - Hash: Key-value pairs (e.g.,
{ "name" => "Alice", "age" => 25 }
).
Type Conversion
You can convert between data types using methods like to_i
, to_f
, to_s
, etc.
num = "10"
puts num.to_i + 5 # Converts string to integer
puts num.to_f # Converts string to float
String Interpolation
Embed variables directly into strings using #{}
.
name = "Alice"
age = 25
puts "Hello, my name is #{name} and I am #{age} years old."
Arrays and Hashes
Arrays and hashes are powerful data structures in Ruby.
# Array Example
fruits = ["apple", "banana", "cherry"]
puts fruits[1] # Output: banana
# Hash Example
person = { "name" => "Alice", "age" => 25 }
puts person["name"] # Output: Alice
Interactive Code Examples
Try running these examples in your Ruby environment to see how they work!
# Interactive Example
puts "Enter your name:"
name = gets.chomp
puts "Hello, #{name}!"
Practice Problems
Test your understanding with these practice problems:
- Write a Ruby program to convert a string to an integer and add 10 to it.
- Write a Ruby program to create an array of numbers and find the sum of all elements.
- Write a Ruby program to create a hash with your name and age, then print it.