Ruby is a versatile and beginner-friendly language, yet it also possesses the depth to satisfy advanced programming needs. In this article, we’ll explore five Ruby programming examples, each progressively more complex, suitable for learners transitioning from beginners to pro-level.
1. Beginner: Hello World
The quintessential starting point for any programming journey is the “Hello, World!” program. It’s simple, but it teaches the basics of code structure and output.
puts "Hello, World!"
2. Intermediate Beginner: Basic Calculator
A step up involves creating a simple calculator that performs basic arithmetic operations. This example introduces user input and basic arithmetic.
puts "Enter the first number:"
number1 = gets.chomp.to_i
puts "Enter the second number:"
number2 = gets.chomp.to_i
sum = number1 + number2
puts "The sum is #{sum}"
3. Intermediate: Building a To-Do List
Creating a to-do list involves arrays and user input, providing a more complex challenge for intermediate learners. It demonstrates basic data structure manipulation.
tasks = []
loop do
puts "Enter a task or 'done':"
input = gets.chomp
break if input.downcase == 'done'
tasks << input
puts "Tasks: #{tasks.join(', ')}"
end
4. Advanced Intermediate: File Operations
As we move towards more advanced territory, handling file operations is crucial. This example involves reading from and writing to files.
File.open("sample.txt", "w") do |file|
file.puts "This is a test file."
end
content = File.read("sample.txt")
puts "File content: #{content}"
5. Pro: Web Scraper with Nokogiri
Finally, a pro-level example involves using an external gem, Nokogiri, to scrape data from web pages. This introduces gems, HTTP requests, and data parsing.
require 'nokogiri'
require 'open-uri'
url = "https://example.com"
document = Nokogiri::HTML(URI.open(url))
headlines = document.css('h1').map(&:text)
puts "Headlines from #{url}: #{headlines}"
Conclusion
These five Ruby programming examples showcase the journey from basic syntax understanding to implementing more complex concepts like file handling and web scraping. Each example builds on the previous one, reinforcing and expanding your Ruby knowledge and skills. Ruby’s elegant syntax and powerful capabilities make it an excellent choice for programmers at any level, offering a smooth learning curve with the potential to handle complex programming challenges.