Variables and Data Types
Ruby supports several data types, including numbers, strings, arrays, and hashes. Defining a variable doesn't require a specific type. Here's an example:
name = "John Doe"
age = 30
In this code, name is a string and age is an integer. Ruby dynamically assigns the data type based on the value the variable holds.
Control Structures
Like most programming languages, Ruby has control structures such as if, else, while, and for.
Ruby
age = 18
if age >= 18
puts "You are eligible to vote."
else
puts "You are not eligible to vote."
end
You can also try this code with Online Ruby Compiler
Run Code
This code will output "You are eligible to vote." since the age is equal to 18.
Methods
Methods in Ruby can be defined using the def keyword. Here's an example:
Ruby
def greet(name)
puts "Hello, #{name}!"
end
greet("Alice")
You can also try this code with Online Ruby Compiler
Run Code
This will output: "Hello, Alice!". The #{name} syntax is used to interpolate the variable name into the string.
Classes and Objects
Ruby is an object-oriented language, so you can define classes and create objects of those classes.
Ruby
class Person
def initialize(name)
@name = name
end
def greet
puts "Hello, #{@name}!"
end
end
person = Person.new("Bob")
person.greet
You can also try this code with Online Ruby Compiler
Run Code
This code defines a Person class with a constructor and a greet method, then creates an object of that class and calls the method.
Frequently Asked Questions
Do I need to declare variable types in Ruby?
No, Ruby is dynamically typed. The interpreter determines the type of the variable at runtime.
What does the @ symbol mean in Ruby?
The @ symbol denotes instance variables in Ruby. They hold values that are accessible within an instance of a class.
How does Ruby handle errors?
Ruby handles errors using a system of exceptions and rescue clauses to catch and handle these exceptions.
Conclusion
Ruby's syntax is known for its elegance and simplicity, designed to make the code more readable and understandable. From basic constructs to variables, control structures, methods, and classes, Ruby offers a broad set of tools with an easy-to-understand syntax. It's a great language for beginners and a joy for experienced developers. Happy coding with Ruby