Ruby Basics
Learn the basics of Ruby
Ruby Basics
Contents
Introduction
Ruby is a high-level, interpreted programming language that emphasizes simplicity and productivity. Its syntax is designed to be easy to read and write.
Installation
Before you can start coding in Ruby, you need to install it on your computer. Visit Ruby's official download page for instructions on how to do this.
Data Types
Ruby has several built-in data types, including:
- Numbers:
123
,3.14
- Strings:
'hello'
,"world"
- Arrays:
[1, 2, 3]
,['a', 'b', 'c']
- Hashes:
{'name' => 'John', 'age' => 30}
Here's how you can create variables of different data types:
number = 123
string = 'hello'
array = [1, 2, 3]
hash = {'name' => 'John', 'age' => 30}
Control Structures
Ruby has various control structures for decision making and looping, including if..else
, case..when
, while
, until
, and for
.
# if..else
if number > 0
puts 'Positive'
else
puts 'Negative or zero'
end
# case..when
case greeting
when 'hello'
puts 'Greeting received'
else
puts 'No greeting received'
end
# while
while number < 10
puts number
number += 1
end
Methods
Methods in Ruby are defined using the def
keyword:
def say_hello
puts 'Hello, world!'
end
# Call the method
say_hello
Methods can also take parameters:
def greet(name)
puts "Hello, #{name}!"
end
# Call the method with an argument
greet('John')
Classes
Ruby is an object-oriented language, so you can define classes to create objects:
class Person
def initialize(name)
@name = name
end
def greet
puts "Hello, #{@name}!"
end
end
# Create an object
john = Person.new('John')
# Call a method on the object
john.greet
Conclusion
This module has provided a brief introduction to Ruby. There's a lot more to learn, but this should give you a good foundation to start from. Happy coding!