Ruby is a dynamic, open-source programming language with a focus on simplicity and productivity. This section provides a comprehensive guide to the syntax of Ruby, covering fundamental concepts and advanced features.

Basic Syntax

Ruby has a very readable syntax that is easy to learn and use. Here are some basic elements of Ruby syntax:

  • Variables: Variables are used to store data values. In Ruby, variables are prefixed with a dollar sign ($ for global variables, @ for instance variables, and no prefix for local variables).

    x = 5
    puts x
    
  • Strings: Strings are used to represent text. Ruby supports both single ('...') and double ("...") quotes for strings.

    puts "Hello, world!"
    puts 'Hello, world!'
    
  • Arrays: Arrays are ordered collections of objects. Ruby arrays are 0-indexed.

    numbers = [1, 2, 3, 4, 5]
    puts numbers[0]  # Outputs: 1
    
  • Hashes: Hashes are unordered collections of key-value pairs.

    person = {"name" => "Alice", "age" => 25}
    puts person["name"]  # Outputs: Alice
    

Control Structures

Ruby provides a variety of control structures to control the flow of execution.

  • If/Else: Used for conditional execution.

    if x > 5
      puts "x is greater than 5"
    else
      puts "x is not greater than 5"
    end
    
  • Loops: Ruby supports several types of loops, including for, while, and each.

    for i in 1..5
      puts i
    end
    

Methods

Methods are functions in Ruby. They can take parameters and return values.

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

greet("Alice")

Blocks

Blocks are chunks of code that can be passed around and executed. They are similar to lambda functions in other languages.

[1, 2, 3].each do |number|
  puts number * 2
end

Ruby on Rails

Ruby on Rails is a popular web application framework that uses Ruby. It provides a convention-over-configuration philosophy that makes it easy to build web applications.

Learn more about Ruby on Rails

Conclusion

Ruby's syntax is designed to be intuitive and easy to learn. By understanding the basic syntax, control structures, methods, and blocks, you'll be well on your way to becoming a proficient Ruby programmer.

Ruby Logo