Start Coding

Topics

Introduction to Ruby

Ruby is a dynamic, object-oriented programming language known for its simplicity and productivity. Created by Yukihiro Matsumoto in 1995, Ruby has gained popularity for its elegant syntax and powerful features.

Why Choose Ruby?

Developers love Ruby for several reasons:

  • Readable and expressive syntax
  • Strong object-oriented programming support
  • Rich standard library
  • Active community and extensive gem ecosystem
  • Great for web development with frameworks like Ruby on Rails

Getting Started with Ruby

To begin your Ruby journey, you'll need to install Ruby on your system. Once installed, you can start writing and running Ruby code.

Your First Ruby Program

Let's create a simple "Hello, World!" program to get started:

puts "Hello, World!"

Save this code in a file with a .rb extension (e.g., hello.rb) and run it using the Ruby interpreter:

ruby hello.rb

Ruby Syntax Basics

Ruby's syntax is designed to be intuitive and easy to read. Here are some key points:

Variables and Data Types

Ruby uses dynamic typing, which means you don't need to declare variable types explicitly. Variables are created when you first assign a value to them:


name = "Alice"
age = 30
height = 1.75
is_student = true
    

Control Structures

Ruby provides various control structures for decision-making and looping:


# If-else statement
if age >= 18
  puts "You're an adult"
else
  puts "You're a minor"
end

# While loop
counter = 0
while counter < 5
  puts "Counter: #{counter}"
  counter += 1
end
    

Methods

Defining methods in Ruby is straightforward:


def greet(name)
  puts "Hello, #{name}!"
end

greet("Ruby Beginner")
    

Object-Oriented Programming in Ruby

Ruby is a pure object-oriented language. Everything in Ruby is an object, including numbers and strings. Here's a simple class definition:


class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def introduce
    puts "Hi, I'm #{@name} and I'm #{@age} years old."
  end
end

alice = Person.new("Alice", 30)
alice.introduce
    

Next Steps

As you continue your Ruby journey, explore these important concepts:

Ruby's rich ecosystem and friendly community make it an excellent choice for beginners and experienced developers alike. Happy coding!