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.
Developers love Ruby for several reasons:
To begin your Ruby journey, you'll need to install Ruby on your system. Once installed, you can start writing and running Ruby code.
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's syntax is designed to be intuitive and easy to read. Here are some key points:
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
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
Defining methods in Ruby is straightforward:
def greet(name)
puts "Hello, #{name}!"
end
greet("Ruby Beginner")
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
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!