Home Current Downloads Blog Contact Us

Ruby Code Examples: A Beginner-Friendly Guide with Practical Snippets

ruby code examples

Ruby is a versatile and expressive scripting language used in both front-end and back-end web development. Known for its elegance and readability, Ruby is an object-oriented language that feels natural to write and easy to understand. Many developers describe Ruby code as being nearly as intuitive as writing in English. Whether you’re new to programming or an experienced developer exploring Ruby, this article presents a range of Ruby code examples to help you understand the syntax, features, and best practices. From simple output to string manipulation, arrays, and object-oriented programming, these examples are designed to be both educational and practical.


Getting Started: Your First Ruby Code Example

Let’s start with the most basic Ruby script—printing output to the screen.

rubyCopyEdit# Using puts (adds a new line at the end)
puts "Hello World!"

# Using print (no newline by default)
print "Hello World!"

Output:

nginxCopyEditHello World!
Hello World!

The puts method appends a newline after outputting the string, while print keeps the cursor on the same line. These are your go-to methods for displaying results in the terminal.


Ruby Code Example: Adding Two Numbers

You can use Ruby to perform arithmetic operations easily. Here’s how you can add two integers entered by the user:

rubyCopyEditputs "Enter first number:"
num1 = gets.chomp.to_i

puts "Enter second number:"
num2 = gets.chomp.to_i

sum = num1 + num2

puts "The sum is #{sum}"

Output Example:

pythonCopyEditEnter first number:
25
Enter second number:
75
The sum is 100

Key Concepts Used:

  • gets to take user input
  • chomp to remove the newline character
  • .to_i to convert string input to an integer
  • String interpolation #{} to include variables in strings

Working with Strings in Ruby

Strings are fundamental in Ruby, and the language provides many ways to handle them effectively.

rubyCopyEdita = 17

puts "a = #{a}"     # double quotes allow interpolation
puts 'a = #{a}'     # single quotes print the literal string

# Multi-line string using heredoc
long_string = <<~TEXT
  This is a multi-line string.
  It can contain instructions or formatted text.
  The value of a is #{a}.
TEXT

puts long_string

Advanced String Operations:

rubyCopyEdits = "Good morning. How are you?"

puts "Length: #{s.length}"
puts "Character at index 4: #{s[4]}"         # returns ASCII code
puts "Character as char: #{s[4].chr}"        # convert ASCII to character
puts "Substring (4,4): #{s[4,4]}"
puts "Substring (6..15): #{s[6..15]}"
puts "Repetition: " + "Wow " * 3
puts "Index of 'How': #{s.index("How")}"
puts "Reversed: #{s.reverse}"

Ruby Code Example: Arrays and Their Operations

Arrays are ordered collections and play a vital role in Ruby.

rubyCopyEditarr1 = [45, 3, 19, 8]
arr2 = ['sam', 'max', 56, 98.9, 3, 10, 'jill']

# Combining arrays
combined = arr1 + arr2
puts "Combined Array: #{combined.join(' ')}"

# Accessing elements
puts "arr1[2]: #{arr1[2]}"
puts "arr2[4]: #{arr2[4]}"
puts "arr2[-2]: #{arr2[-2]}"

# Sorting and appending
puts "Sorted arr1: #{arr1.sort.join(' ')}"
arr1 << 57 << 9 << 'phil'
puts "Extended arr1: #{arr1.join(' ')}"

Manipulating Arrays: Push, Pop, Shift, and Delete

rubyCopyEditb = ['Brian', 48, 220]

b << 'alex' << 90
puts "Array B: #{b.join(', ')}"

puts "Popped: #{b.pop}"
puts "Shifted: #{b.shift}"
puts "After deletions: #{b.join(', ')}"

b.delete_at(1)      # delete by index
b.delete('alex')    # delete by value
puts "Final Array: #{b.join(', ')}"

Ruby Code Example: Calculating the Area of a Rectangle

rubyCopyEditputs "Enter length:"
length = gets.chomp.to_f

puts "Enter width:"
width = gets.chomp.to_f

area = length * width
puts "Area of Rectangle is #{area}"

Sample Output:

mathematicaCopyEditEnter length:
10.5
Enter width:
4
Area of Rectangle is 42.0

Ruby Code Example: Sum of Even Numbers up to N

This example uses a while loop to compute the sum of even numbers:

rubyCopyEditputs "Enter a number:"
n = gets.chomp.to_i

sum = 0
i = 1

while i <= n
  sum += i if i % 2 == 0
  i += 1
end

puts "The sum of even numbers up to #{n} is #{sum}"

Try running it with values like 10 or 60 to see different results.


Object-Oriented Ruby: Defining Classes

Ruby’s object-oriented nature makes it easy to create and work with custom classes.

rubyCopyEditclass Upstack
  def initialize(value)
    @val = value
  end

  def set(value)
    @val = value
  end

  def get
    @val
  end
end

a = Upstack.new(10)
b = Upstack.new(22)

puts "Initial values: A = #{a.get}, B = #{b.get}"
b.set(34)
puts "Updated B: A = #{a.get}, B = #{b.get}"

Extending Classes and Defining Singleton Methods

rubyCopyEditclass Fred
  def inc
    @val ||= 0
    @val += 1
  end
end

# Adding a method only to instance 'b'
def b.dec
  @val ||= 0
  @val -= 1
end

# Use exception handling
begin
  a.inc
  b.inc
  b.dec
  a.dec  # This will throw an error as `a` has no `dec`
rescue StandardError => e
  puts "Error caught: #{e.message}"
end

Best Practices for Writing Clean Ruby Code

  1. Use Meaningful Variable Names
    Avoid generic names like x or val unless they’re contextually clear.
  2. Leverage Ruby’s Expressiveness
    Prefer each, map, and select over raw loops for readability.
  3. String Interpolation
    Use #{} for embedding variables or expressions inside double-quoted strings.
  4. Use Symbols When Appropriate
    Symbols (e.g., :name) are lightweight and faster than strings for identifiers.
  5. Stick to Snake_case
    Method and variable names should use snake_case as per Ruby conventions.
  6. Comment Judiciously
    Use comments to clarify “why” something is done, not just “what.”

Additional Ruby Code Example: FizzBuzz Logic

FizzBuzz is a classic beginner problem:

rubyCopyEdit(1..20).each do |i|
  if i % 15 == 0
    puts "FizzBuzz"
  elsif i % 3 == 0
    puts "Fizz"
  elsif i % 5 == 0
    puts "Buzz"
  else
    puts i
  end
end

Ruby Code Example: Using Hashes

Hashes are key-value pairs in Ruby.

rubyCopyEditperson = {
  name: "Alice",
  age: 30,
  city: "New York"
}

puts "Name: #{person[:name]}"
puts "Age: #{person[:age]}"
puts "City: #{person[:city]}"

You can also iterate:

rubyCopyEditperson.each do |key, value|
  puts "#{key.capitalize}: #{value}"
end

Final Thoughts

These Ruby code examples illustrate the language’s flexibility and clarity, making it ideal for beginners and experienced developers alike. From basic syntax and string handling to object-oriented design and real-world use cases like calculating sums or managing arrays, Ruby offers elegant solutions with minimal code.

The more you practice writing and reading Ruby, the more you’ll appreciate its clean design and expressiveness. Bookmark this guide as your go-to reference for practical Ruby code snippets as you continue to level up your programming skills.

Leave a Reply

Your email address will not be published. Required fields are marked *