Ruby Syntax

Ruby is a high-level, interpreted language with a syntax that is easy to read and write. Here's a basic tutorial on Ruby syntax:

1. Comments

In Ruby, any line that begins with a hash symbol # is a comment and will be ignored by the interpreter.

# This is a comment

2. Variables

Ruby uses snake_case for variable naming. You don't need to specify the type of data that a variable will contain.

name = "Alice"
age = 30

3. Data Types

Ruby has several built-in data types:

  • Numbers: 123, 3.14
  • Strings: "Hello, world!"
  • Symbols: :symbol
  • Arrays: [1, 2, 3, 4]
  • Hashes: { "key" => "value", "another_key" => "another_value" }
  • Booleans: true, false
  • Nil: nil

4. Control Flow

Ruby has the usual control flow constructs:

  • if, elsif, and else:
if age > 30
  puts "You are old"
elsif age > 20
  puts "You are young"
else
  puts "You are very young"
end
  • unless (the opposite of if):
unless age > 30
  puts "You are not old"
end
  • while:
while age < 50
  puts "You are not 50 yet"
  age += 1
end
  • for:
for i in 0..5
  puts "Number #{i}"
end

5. Methods

You can define a method using the def keyword:

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

greet("Alice")  # Outputs: Hello, Alice!

6. Classes

You can define a class using the class keyword:

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

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

alice = Person.new("Alice", 30)
alice.greet  # Outputs: Hello, Alice!

7. Blocks

Blocks are anonymous pieces of code that can accept input and are used extensively in Ruby, especially with iterators:

3.times do |i|
  puts "Hello, world! #{i}"
end

[1, 2, 3, 4].each { |number| puts number * 2 }

This is a very basic introduction to Ruby syntax. Ruby has many more features that make it a powerful and flexible language, but this should be enough to get you started.