Ruby CLI Playground Online
Simulate a Ruby terminal in your browser to test scripts and practice syntax quickly.
π― Recommended Ruby courses just for you
Loading...
π‘ Ruby Basics Guide for Beginners
1. Declaring Variables and Constants
Ruby is dynamically typed. Constants start with uppercase letters and are not meant to change.
x = 10
pi = 3.14
name = "Alice"
is_active = true
MAX_USERS = 100
APP_NAME = "CodeUtility"
2. Conditionals (if / case)
Use if
, elsif
, else
, or case
for control flow.
x = 2
if x == 1
puts "One"
elsif x == 2
puts "Two"
else
puts "Other"
end
case x
when 1
puts "One"
when 2
puts "Two"
else
puts "Other"
end
3. Loops
Use while
, until
, or iterators like each
.
i = 0
while i < 3
puts i
i += 1
end
[1, 2, 3].each do |n|
puts n
end
4. Arrays
Arrays store ordered lists of elements. Access using indexes.
fruits = ["apple", "banana", "cherry"]
puts fruits[0]
puts fruits.length
5. Array Manipulation
Use push
, pop
, slice
, and reverse
for working with arrays.
fruits.push("kiwi")
fruits.pop
puts fruits[1..2]
puts fruits.reverse
# Array comprehension
squares = (1..5).map { |x| x * x }
puts squares
6. Console Input/Output
Use gets.chomp
to read input and puts
/print
for output.
print "Enter your name: "
name = gets.chomp
puts "Hello, #{name}"
7. Functions
Define functions using def
. You can pass arguments and return values.
def greet(name)
"Hello, #{name}"
end
puts greet("Alice")
8. Hashes
Hashes are key-value pairs, like dictionaries or maps.
person = { "name" => "Bob", "age" => 25 }
puts person["name"]
# Symbol keys
person = { name: "Alice", age: 30 }
puts person[:name]
9. Exception Handling
Use begin-rescue-end
to catch exceptions and handle errors gracefully.
begin
raise "Something went wrong"
rescue => e
puts e.message
end
10. File I/O
Read and write files using File
methods or IO
classes.
File.write("file.txt", "Hello File")
content = File.read("file.txt")
puts content
11. String Manipulation
Ruby strings support many methods: length
, gsub
, split
, etc.
text = " Hello World "
puts text.strip
puts text.upcase
puts text.gsub("Hello", "Hi")
puts text.split
12. Classes & Objects
Ruby is fully object-oriented. Use initialize
to define constructors.
class Person
def initialize(name)
@name = name
end
def greet
"Hi, I'm #{@name}"
end
end
p = Person.new("Alice")
puts p.greet
13. References (Object Mutation)
All variables hold references to objects. Modifying an object inside a function affects the original.
def modify(arr)
arr << "changed"
end
data = ["original"]
modify(data)
puts data.inspect # ["original", "changed"]