
Variables: In Ruby, variables are used to store values that can be used later in the program. Variable names start with a lowercase letter or underscore and can contain letters, numbers, and underscores. Here's an example of defining and using a variable:
name = "Alice"
puts "Hello, #{name}!"
This code defines a variable name with the value "Alice", and then uses that variable in a string interpolation to print out the message "Hello, Alice!".Data types: Ruby has several built-in data types, including strings, numbers, booleans, arrays, and hashes. Here are some examples:
# Strings
greeting = "Hello, world!"
puts greeting
# Numbers
x = 42
y = 3.14
puts x + y
# Booleans
is_ruby_fun = true
puts "Is Ruby fun? #{is_ruby_fun}"
# Arrays
fruits = ["apple", "banana", "orange"]
puts fruits[1]
# Hashes
person = { "name" => "Bob", "age" => 30 }
puts person["name"]
This code defines variables of various data types and uses them in different ways.
Operators: Ruby has a variety of operators for performing arithmetic, comparisons, and logical operations. Here are some examples:
Control structures: Ruby has several control structures, including if statements, while loops, for loops, and iterators like each. Here are some examples:
These are just a few examples of the basic syntax of Ruby. As you learn more about the language, you'll discover many more features and capabilities that make Ruby a powerful and expressive programming language.
# Arithmetic operators
x = 10
y = 3
puts x + y
puts x - y
puts x * y
puts x / y
puts x % y
# Comparison operators
puts 2 == 2
puts 2 != 3
puts 2 < 3
puts 2 <= 3
puts 2 > 3
puts 2 >= 3
# Logical operators
puts true && false
puts true || false
puts !true
Control structures: Ruby has several control structures, including if statements, while loops, for loops, and iterators like each. Here are some examples:
# if statement
x = 5
if x > 10
puts "x is greater than 10"
else
puts "x is less than or equal to 10"
end
# while loop
i = 0
while i < 5
puts i
i += 1
end
# for loop
for i in 1..5
puts i
end
# each iterator
fruits = ["apple", "banana", "orange"]
fruits.each do |fruit|
puts fruit
end
These are just a few examples of the basic syntax of Ruby. As you learn more about the language, you'll discover many more features and capabilities that make Ruby a powerful and expressive programming language.

0 Comments