CodeToLive

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:

Common Data Types

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:

  1. Write a Ruby program to convert a string to an integer and add 10 to it.
  2. Write a Ruby program to create an array of numbers and find the sum of all elements.
  3. Write a Ruby program to create a hash with your name and age, then print it.
Next: Control Structures