Here's a basic tutorial for Ruby programming, introducing some key elements of the language.
1. Installing Ruby
Before you start coding, you need to ensure that Ruby is installed on your machine. If you're on a Unix-like system such as Linux or MacOS, you likely already have Ruby installed. You can check by typing ruby -v
in your terminal. If Ruby is not installed, you can download it from the official Ruby website or use a version manager like rbenv
or rvm
.
2. Your First Ruby Program
Once Ruby is installed, you can write your first Ruby program. Open a text editor, type the following line, and save the file as hello_world.rb
:
puts "Hello, world!"
You can run this program by typing ruby hello_world.rb
in your terminal. You should see the text "Hello, world!" printed in the console.
3. Variables and Data Types
Ruby has several basic data types, including numbers, strings, arrays, and hashes:
# This is a comment number = 5 # Integer pi = 3.14 # Float name = "Alice" # String is_tall = true # Boolean fruits = ["apple", "banana", "cherry"] # Array person = { "name" => "Alice", "age" => 30 } # Hash
4. Control Flow
Ruby has several control flow structures, including if
, else
, while
, for
, and case
:
age = 18 if age >= 18 puts "You are an adult" else puts "You are a minor" end
5. Loops
Here's an example of a loop in Ruby:
5.times do |i| puts "This is iteration number #{i}" end
6. Methods
You can define methods in Ruby using the def
keyword:
def greet(name) puts "Hello, #{name}!" end greet("Alice")
7. Classes
Ruby is an object-oriented language, and you can define classes like this:
class Person def initialize(name, age) @name = name @age = age end def introduce puts "Hello, my name is #{@name} and I'm #{@age} years old." end end alice = Person.new("Alice", 30) alice.introduce
8. Gems
Ruby has a rich ecosystem of libraries, known as gems. You can install a gem with the command gem install <gem_name>
. For example, to install the popular HTTP library httparty
, you would run gem install httparty
.
This is a very basic introduction to Ruby. The language has many more features, including modules, error handling, file I/O, and more.
Ruby Tutorial
Ruby CGI
Ruby Advanced