Skip to content
DevNursery.com - New Web Developer Docs
GitHub

Ruby

Basic Ruby Syntax

Ruby is a dynamic, object-oriented programming language known for its simplicity and productivity. In this section, we’ll cover the basic syntax of Ruby to help you get started.

1. Comments

In Ruby, you can add comments using the # symbol. Comments are ignored by the Ruby interpreter and are useful for documenting your code.

# This is a single-line comment

=begin
This is a
multi-line comment
=end

2. Output

You can display output in Ruby using the puts (put string) or print methods.

puts "Hello, Ruby!" # Prints with a newline
print "Hello, Ruby!" # Prints without a newline

3. Variables and Data Types

Ruby is dynamically typed, meaning you don’t need to declare the data type of a variable explicitly.

name = "John" # String
age = 30 # Integer
height = 6.2 # Float
is_student = true # Boolean

4. Strings

Ruby supports single-quoted (’) and double-quoted (”) strings. Double-quoted strings allow for string interpolation.

single_quoted = 'This is a single-quoted string.'
double_quoted = "Hello, #{name}!" # String interpolation

5. Numbers

Ruby supports integers and floating-point numbers.

integer_number = 42
float_number = 3.14

6. Arrays

Arrays are ordered collections of elements, and they can contain different data types.

fruits = ["apple", "banana", "cherry"]

7. Hashes

Hashes, also known as dictionaries or associative arrays, store key-value pairs.

person = {
  "name" => "John",
  "age" => 30,
}

8. Control Structures

Ruby provides common control structures like if, else, elsif, unless, case, and loops (while, until, for, each).

if age >= 18
  puts "You are an adult."
else
  puts "You are a minor."
end

9. Functions (Methods)

You can define functions using the def keyword. Ruby functions return the result of the last executed statement.

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

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

10. Symbols

Symbols are lightweight strings often used as keys in hashes.

:my_symbol

11. Classes and Objects

Ruby is an object-oriented language, and you can define classes and create objects.

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

  def say_hello
    "Hello, #{@name}!"
  end
end

john = Person.new("John")
puts john.say_hello # Outputs: Hello, John!

12. Exception Handling

Ruby uses begin, rescue, and end for exception handling.

begin
  result = 10 / 0
rescue ZeroDivisionError
  puts "Error: Division by zero!"
end

13. Symbols and Blocks

Symbols are often used in Ruby for efficiency, and blocks are used for defining anonymous functions.

# Symbol
:my_symbol

# Block
[1, 2, 3].each do |number|
  puts number
end

Ruby Functions

n Ruby, functions are known as methods, and they play a crucial role in organizing and encapsulating code. In this section, we’ll cover the basic syntax of Ruby methods, including how to define them, work with arguments, return values, and use procs and blocks.

1. Defining Methods

In Ruby, you define methods using the def keyword, followed by the method name, parentheses for arguments (if any), and an end to signify the method’s body.

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

2. Calling Methods

To call a method, use its name followed by parentheses containing the arguments (if any).

result = greet("Alice")
puts result # Outputs: Hello, Alice!

3. Method Arguments

Ruby methods can take zero or more arguments. You can define methods with required, optional, or default arguments.

def add(x, y)
  x + y
end

puts add(2, 3) # Outputs: 5

Optional Arguments

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

puts greet("Bob") # Outputs: Hello, Bob!
puts greet("Alice", "Hi") # Outputs: Hi, Alice!

Default Arguments

def divide(x, y = 1)
  x / y
end

puts divide(6) # Outputs: 6
puts divide(6, 2) # Outputs: 3

4. Return Values

Ruby methods return the result of the last executed statement by default. However, you can use the return keyword to explicitly return a value.

def add(x, y)
  result = x + y
  return result
end

sum = add(2, 3)
puts sum # Outputs: 5

5. Procs

A proc is an object that holds a block of code. You can create a proc using the Proc.new or -> syntax. Procs can be stored in variables and passed as arguments to methods.

my_proc = Proc.new { |x| x * 2 }
puts my_proc.call(3) # Outputs: 6

6. Blocks

Blocks are chunks of code enclosed within do…end or curly braces {…}. They are often used with methods that yield control to the block.

[1, 2, 3].each do |number|
  puts number
end

You can define methods that accept blocks using the yield keyword:

def say_hello
  puts "Hello!"
  yield if block_given?
end

say_hello do
  puts "Block executed."
end

# Outputs:
# Hello!
# Block executed.

In Ruby, blocks are commonly used for iterators, custom control structures, and working with collections like arrays and hashes.

Understanding Ruby’s method syntax, argument handling, return values, procs, and blocks is essential for effective Ruby programming. These features make Ruby a versatile language, especially when used in conjunction with libraries and frameworks like Ruby on Rails.

Ruby Classes

Classes are fundamental in Ruby for creating objects and organizing code. In this section, we’ll cover the basic syntax of Ruby classes, including constructors, properties (attributes), methods, inheritance, overriding methods, and the concept of static methods and properties.

1. Basic Syntax

To define a class in Ruby, you use the class keyword, followed by the class name in CamelCase. The class’s code block contains its properties and methods.

class Person
  # Properties and methods go here
end

2. Constructors

In Ruby, the constructor method is named initialize. It’s automatically called when an instance of the class is created using new.

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

person = Person.new("Alice", 30)

3. Properties, Getters, and Setters

Properties in Ruby are instance variables, typically prefixed with @. To access them, you can create getter and setter methods.

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

  # Getter method
  def name
    @name
  end

  # Setter method
  def name=(new_name)
    @name = new_name
  end
end

person = Person.new("Alice")
puts person.name # Outputs: Alice
person.name = "Bob"
puts person.name # Outputs: Bob

You can also use Ruby’s built-in attr_reader, attr_writer, or attr_accessor to generate getter and setter methods automatically.

class Person
  attr_reader :name
  attr_writer :name
  # or attr_accessor :name for both getter and setter
  def initialize(name)
    @name = name
  end
end

4. Methods

Methods in Ruby are defined within the class block. You can call them on instances of the class.

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

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

person = Person.new("Alice")
puts person.greet # Outputs: Hello, Alice!

5. Inheritance

Ruby supports single inheritance, allowing a class to inherit properties and methods from a parent class. Use the < symbol to indicate inheritance.

class Student < Person
  def initialize(name, school)
    super(name)
    @school = school
  end
end

student = Student.new("Bob", "High School")
puts student.greet # Outputs: Hello, Bob!

6. Overriding Methods

Inherited methods can be overridden by defining a method with the same name in the child class. To call the parent class’s method, use the super keyword.

class Student < Person
  def greet
    "Hi, I'm a student named #{@name}!"
  end
end

student = Student.new("Charlie", "College")
puts student.greet # Outputs: Hi, I'm a student named Charlie!

7. Static Methods and Properties

In Ruby, class methods are defined using the self keyword within the class. They are called on the class itself, not on instances.

class MathUtils
  def self.square(x)
    x * x
  end
end

result = MathUtils.square(5)
puts result # Outputs: 25

Class variables are shared across all instances of a class. They are prefixed with @@.

class Counter
  @@count = 0

  def initialize
    @@count += 1
  end

  def self.total_count
    @@count
  end
end

Counter.new
Counter.new
puts Counter.total_count # Outputs: 2

Understanding classes, constructors, properties, methods, inheritance, method overriding, and class-level methods and properties is essential for building robust and organized Ruby applications. Classes are at the core of object-oriented programming in Ruby, allowing you to create reusable and modular code.

Ruby CLI

Running Ruby Scripts

To run Ruby scripts from the command line, use the ruby command followed by the script’s filename. For example:

ruby my_script.rb

You can also run one-liner Ruby code directly from the command line using the -e option:

ruby -e 'puts "Hello, World!"'

Commands for Working with Gems and Gemfiles

1. Installing Gems

To install a Ruby gem, use the gem install command followed by the gem’s name:

gem install gem_name

2. Listing Installed Gems

You can list all the installed gems using:

gem list

3. Running a Ruby Script with Required Gems

To run a Ruby script that depends on specific gems, use the ruby command followed by -r or —require to specify the required gems:

ruby -r gem_name my_script.rb

4. Uninstalling Gems

To uninstall a gem, use the gem uninstall command:

gem uninstall gem_name

5. Updating Gems

You can update a gem to its latest version with:

gem update gem_name
6. Creating Gemfiles

A Gemfile is used to specify project dependencies. To create one, simply create a file named Gemfile in your project’s directory.

Gemfile Syntax Here’s a basic example of a Gemfile:

# Gemfile

# Specify a gem and its version
gem 'rails', '6.1.0'

# Specify multiple gems
gem 'sqlite3', '~> 1.4'
gem 'puma', '~> 3.12'
gem 'sass-rails', '>= 6'

# Groups for different environments (e.g., development, test, production)
group :development, :test do
  gem 'rspec-rails', '~> 5.0'
  gem 'pry'
end

group :production do
  gem 'pg', '>= 1.2', '< 2.0'
end

In the Gemfile:

Use the gem keyword followed by the gem name and its version or version constraints. You can group gems using group to specify dependencies for different environments (e.g., development, test, production). ~> specifies a version constraint, allowing versions up to the specified version. >= and < are used to specify version ranges. After creating or editing the Gemfile, you need to run bundle install to install the specified gems.

Running Bundler

To install all the gems listed in the Gemfile and create a Gemfile.lock file, run:

bundle install

This ensures that all project collaborators use the same gem versions.

Ruby’s CLI, along with Gemfiles and the Bundler tool, are essential for managing dependencies and running Ruby scripts and applications effectively.

Built-in Ruby Functions & Methods

1-25

MethodPurposeSyntaxExample
putsOutput text to the consoleputs(string)puts "Hello, Ruby!"
printOutput text to the console without a newlineprint(string)print "Hello, " print "Ruby!"
getsRead a line of text from the consolegetsname = gets.chomp
chompRemove trailing newline characters from a stringchompinput = gets.chomp
to_iConvert a string to an integerto_inum_str = "42" num = num_str.to_i
to_fConvert a string to a floating-point numberto_fnum_str = "3.14" num = num_str.to_f
to_sConvert an object to a stringto_snum = 42 str = num.to_s
lengthGet the length of a stringlengthlen = "Hello".length
upcaseConvert a string to uppercaseupcasetext = "hello".upcase
downcaseConvert a string to lowercasedowncasetext = "HELLO".downcase
stripRemove leading and trailing whitespace from a stringstriptext = " hello ".strip
splitSplit a string into an array using a delimitersplit(delimiter)words = "Hello,World".split(",")
concatAppend one string to anotherconcat(string)str1 = "Hello," str2 = " Ruby!" str1.concat(str2)
include?Check if a string contains another substringinclude?(substring)text = "Hello, Ruby!" text.include?("Ruby")
empty?Check if a string is emptyempty?str = "" empty = str.empty?
reverseReverse the characters in a stringreversestr = "hello".reverse
gsubReplace all occurrences of a substring in a stringgsub(pattern, replacement)text = "Hello, world!" text.gsub("world", "Ruby")
matchFind the first occurrence of a pattern in a stringmatch(pattern)text = "Hello, Ruby!" match = text.match(/R\w+/)
capitalizeCapitalize the first character of a stringcapitalizetext = "hello".capitalize
joinConcatenate elements of an array into a stringjoin(delimiter)arr = ["Hello", "Ruby"] str = arr.join(" ")
to_symConvert a string to a symbolto_symstr = "variable_name" sym = str.to_sym
randGenerate a random numberrand(range)random_number = rand(1..10)
include? (Array)Check if an array includes a specific elementinclude?(element)arr = [1, 2, 3] included = arr.include?(2)
pushAppend an element to an arraypush(element)arr = [1, 2] arr.push(3)
popRemove and return the last element from an arraypoparr = [1, 2, 3] last_element = arr.pop

26-50

MethodPurposeSyntaxExample
absGet the absolute value of a numberabsnum = -5 num.abs
ceilRound a float up to the nearest integerceilnum = 3.2 num.ceil
floorRound a float down to the nearest integerfloornum = 3.8 num.floor
roundRound a float to the nearest integerroundnum = 3.5 num.round
timesExecute a block of code a specified number of timestimes3.times { puts "Hello" }
uptoIterate over a range of numbersupto(limit)`1.upto(5) {
downtoIterate over a range of numbers in reversedownto(limit)`5.downto(1) {
mapCreate a new array by applying a block to each element`map {e
eachIterate over elements of an array`each {e
selectCreate a new array with elements that satisfy a condition`select {e
rejectCreate a new array with elements that do not satisfy a condition`reject {e
sortSort an array in ascending ordersortarr = [3, 1, 2] sorted = arr.sort
sort!Sort an array in ascending order in placesort!arr = [3, 1, 2] arr.sort!
reverse (Array)Reverse the elements of an arrayreversearr = [1, 2, 3] reversed = arr.reverse
uniqRemove duplicate elements from an arrayuniqarr = [1, 2, 2, 3, 3] unique = arr.uniq
empty? (Array)Check if an array is emptyempty?arr = [] empty = arr.empty?
size (Array)Get the number of elements in an arraysizearr = [1, 2, 3] size = arr.size
first (Array)Get the first element of an arrayfirstarr = [1, 2, 3] first_element = arr.first
last (Array)Get the last element of an arraylastarr = [1, 2, 3] last_element = arr.last
min (Array)Find the minimum element in an arrayminarr = [5, 2, 8] min_value = arr.min
max (Array)Find the maximum element in an arraymaxarr = [5, 2, 8] max_value = arr.max
sum (Array)Calculate the sum of elements in an arraysumarr = [1, 2, 3] sum_result = arr.sum
zipCombine multiple arrays into one array of arrayszip(array)arr1 = [1, 2] arr2 = ['a', 'b'] zipped = arr1.zip(arr2)
flattenFlatten a nested arrayflatten`nested_arr = [1, [2, [3,

51-75

MethodPurposeSyntaxExample
concat (Array)Concatenate two arraysconcat(array)arr1 = [1, 2] arr2 = [3, 4] arr1.concat(arr2)
join (Array)Combine array elements into a stringjoin(separator)arr = ['apple', 'banana', 'cherry'] str = arr.join(', ')
split (String)Split a string into an array using a delimitersplit(delimiter)str = 'apple,banana,cherry' arr = str.split(',')
chomp (String)Remove trailing newline character from a stringchompstr = "Hello\n" chomped = str.chomp
strip (String)Remove leading and trailing whitespaces from a stringstripstr = " Hello " stripped = str.strip
gsub (String)Replace all occurrences of a substring in a stringgsub(pattern, replacement)str = 'Hello, World!' replaced = str.gsub('Hello', 'Hi')
include? (String)Check if a string contains another substringinclude?(substring)str = 'Hello, World!' contains = str.include?('Hello')
upcase (String)Convert a string to uppercaseupcasestr = 'hello' upcased = str.upcase
downcase (String)Convert a string to lowercasedowncasestr = 'HELLO' downcased = str.downcase
capitalize (String)Capitalize the first letter of a stringcapitalizestr = 'hello' capitalized = str.capitalize
reverse (String)Reverse the characters of a stringreversestr = 'hello' reversed = str.reverse
strip (String)Remove leading and trailing whitespaces from a stringstripstr = " Hello " stripped = str.strip
count (String)Count the occurrences of a substring in a stringcount(substring)str = 'hello world' count = str.count('l')
delete (String)Delete specified characters from a stringdelete(characters)str = 'hello, world!' deleted = str.delete('o')
squeeze (String)Remove repeated adjacent characters in a stringsqueezestr = 'bookkeeping' squeezed = str.squeeze('k')
slice (String)Extract a substring from a stringslice(start, length)str = 'hello, world!' sliced = str.slice(0, 5)
replace (String)Replace the content of a string with another stringreplace(new_string)str = 'Hello' str.replace('Hi')
clear (Array)Remove all elements from an arraycleararr = [1, 2, 3] arr.clear
length (String)Get the length of a stringlengthstr = 'Hello' length = str.length
reverse! (String)Reverse the characters of a string in placereverse!str = 'hello' str.reverse!
insert (String)Insert a string into another string at a specific positioninsert(index, string)str = 'hello' str.insert(3, ', world')
slice! (String)Extract a substring from a string in placeslice!(start, length)str = 'hello, world!' str.slice!(0, 5)
gsub! (String)Replace all occurrences of a substring in a string in placegsub!(pattern, replacement)str = 'Hello, World!' str.gsub!('Hello', 'Hi')

76-100

MethodPurposeSyntaxExample
slice! (Array)Remove and return elements from an arrayslice!(start, length)arr = [1, 2, 3, 4] sliced = arr.slice!(1, 2)
pop (Array)Remove and return the last element from an arraypoparr = [1, 2, 3] last = arr.pop
shift (Array)Remove and return the first element from an arrayshiftarr = [1, 2, 3] first = arr.shift
unshift (Array)Add one or more elements to the beginning of an arrayunshift(element1, element2, ...)arr = [2, 3] arr.unshift(1)
push (Array)Add one or more elements to the end of an arraypush(element1, element2, ...)arr = [1, 2] arr.push(3, 4)
compact (Array)Remove nil values from an arraycompactarr = [1, nil, 2, nil] arr.compact
uniq (Array)Remove duplicate elements from an arrayuniqarr = [1, 2, 1, 3, 2] unique = arr.uniq
sort (Array)Sort elements in an arraysortarr = [3, 1, 2] sorted = arr.sort
max (Array)Find the maximum value in an arraymaxarr = [3, 1, 2] maximum = arr.max
min (Array)Find the minimum value in an arrayminarr = [3, 1, 2] minimum = arr.min
reverse (Array)Reverse the order of elements in an arrayreversearr = [1, 2, 3] reversed = arr.reverse
include? (Array)Check if an array includes a specific elementinclude?(element)arr = [1, 2, 3] includes = arr.include?(2)
each_with_index (Array)Iterate through array elements with their indiceseach_with_index`arr = [‘a’, ‘b’, ‘c’] arr.each_with_index {
map (Array)Create a new array by applying a block to each element`map {element
select (Array)Filter elements in an array based on a condition`select {element
reject (Array)Filter elements in an array based on a condition (opposite of select)`reject {element
find (Array)Find the first element that matches a condition`find {element
reduce (Array)Combine elements in an array with a binary operation`reduce(initial) {memo, element
join (Array)Combine array elements into a string with a separatorjoin(separator)arr = ['apple', 'banana', 'cherry'] str = arr.join(', ')
empty? (Array)Check if an array is emptyempty?`arr = [] empty