Ruby Overview
Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. Ruby is the language behind the Ruby on Rails framework.
Key Features
- Object-Oriented: Everything is an object in Ruby.
- Flexible: Allows changing parts of the language.
- Expressive: Clean, readable syntax.
- Mixins: Share functionality between classes.
- Blocks: Powerful closure-like functionality.
- Metaprogramming: Code that writes code.
- Gems: Rich ecosystem of libraries.
Common Use Cases
Web Development
Ruby on Rails framework for building web applications.
Scripting
Automating tasks and writing utilities.
DevOps Tools
Chef, Puppet, and other automation tools.
Prototyping
Quickly build prototypes and MVPs.
Example Code
# Ruby example demonstrating features
# Class with initialize method
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def greet
"Hello, my name is #{@name}"
end
end
# Module as mixin
module Speak
def speak(text)
puts text
end
end
# Class using mixin
class Dog
include Speak
def initialize(name)
@name = name
end
end
# Using the examples
person = Person.new("Alice", 30)
puts person.greet
dog = Dog.new("Buddy")
dog.speak("Woof!")
# Blocks and enumerables
numbers = [1, 2, 3, 4, 5]
squares = numbers.map { |n| n * n }
puts "Squares: #{squares}"
# Symbol to proc
names = ["alice", "bob", "charlie"]
upcased = names.map(&:upcase)
puts "Upcased: #{upcased}"
# Metaprogramming example
class MyClass
[:a, :b, :c].each do |method|
define_method(method) do
"Method #{method} called"
end
end
end
obj = MyClass.new
puts obj.a
puts obj.b