Your First Ruby Program
Learn to write, save, and run your first Ruby program. Master the basics of Ruby output methods and file execution.
Hello, World!
Learning Objective: Write and run your first Ruby program that outputs "Hello, World!"
Step 1: Create Your First Ruby File
Create a new file called hello.rb
Add this code to hello.rb
Step 2: Run Your Program
Ruby Output Methods
Ruby provides several methods for displaying output. Each has its own characteristics and use cases.
puts Most Common Output Method
puts (put string) outputs text and automatically adds a newline at the end. It's the most commonly used output method.
Example Code
Output
print Output Without Newline
print outputs text without adding a newline at the end. Useful when you want to build output on the same line.
Example Code
Output
p Debugging Output
p is great for debugging. It calls inspect on the object, showing its internal representation.
Example Code
Output
File Extensions & Naming Conventions
Ruby File Convention: Ruby files should end with .rb extension
Ruby Naming Conventions
File Names
- snake_case: hello_world.rb
- descriptive: user_authentication.rb
- lowercase: calculator.rb
Examples
- my_first_program.rb
- temperature_converter.rb
- student_grade_calculator.rb
Practice Examples
Example 1: Personal Greeting
Create greeting.rb
Run and Test
Example 2: Simple Calculator
Create calculator.rb
Best Practices
Ruby Programming Best Practices
- Use descriptive file names: Choose names that clearly indicate what the program does
- Add comments: Use
#to explain complex logic - Use puts for user output: It's the most readable and commonly used method
- Use p for debugging: Great for inspecting variables and data structures
- Keep it simple: Start with basic programs and gradually add complexity
Common Mistakes to Avoid
- Forgetting .rb extension: Always save Ruby files with .rb extension
- Case sensitivity: Ruby is case-sensitive -
putsis different fromPuts - Missing quotes: String literals must be enclosed in quotes
- Wrong file path: Make sure you're in the correct directory when running Ruby files
What's Next?
Continue Your Ruby Journey
- Learn IRB: Start the Interactive Ruby shell with
irb - Explore Variables: Learn about different types of variables in Ruby
- Study Data Types: Understand strings, numbers, arrays, and hashes
- Practice More: Create simple programs to reinforce your learning
- Read Documentation: Learn how to find help and documentation