Introduction to Ruby
Ruby is a powerful, flexible programming language that is popular for web development, game creation, and text processing. It is also the foundation of the widely-used Ruby on Rails framework. Ruby is:
- High-level: Ruby’s syntax is straightforward and easy to read, often resembling English sentences.
- Interpreted: No need for a compiler! You can write and execute Ruby code directly on platforms like Codecademy or on your own machine (as Ruby is typically pre-installed).
- Object-oriented: In Ruby, everything is an object, from numbers to strings, and this makes it a versatile language for creating programs.
- Easy to use: Designed by Yukihiro Matsumoto (aka Matz) in 1995, Ruby emphasizes simplicity and productivity, focusing on the human needs rather than the machine's needs.
Conventions in Ruby
- Case sensitivity: Ruby is case-sensitive. For example,
myVaris different frommyvar. - Variable naming: Local variables should begin with a lowercase letter and use underscores between words (e.g.,
counter,masterful_method). - Whitespace: Ruby ignores extra spaces and blank lines, but Rubyists (enthusiasts of Ruby) follow conventions like indenting blocks with two spaces.
- Class and module names: By convention, class and module names are written in CamelCase (e.g.,
MyClass), while constants are written in ALL_CAPS with underscores (e.g.,MY_CONSTANT).
Ruby Types
Ruby supports a variety of data types, including:
- Numeric: Represents numbers.
- Boolean: Can either be
trueorfalse. - String: Holds text, such as
"I'm learning Ruby!".
Variables in Ruby are used to store values of almost any type, and you do not need to declare a data type when defining them. Here's an example of how to declare a variable:
myVar = 48
Basic Math Operations
Ruby allows basic arithmetic operations:
- Addition:
+ - Subtraction:
- - Multiplication:
* - Division:
/ - Exponentiation:
**(e.g.,2**3equals 8) - Modulo:
%(returns the remainder of division)
Output: puts vs print
Ruby provides two ways to display output:
print: Displays content without a newline.puts: Adds a newline after the content.
Example:
puts "Hello".reverse # => "olleH"
Comments in Ruby
- Single-line comments: Use the
#symbol.
# This is a comment
- Multi-line comments: Use
=beginand=end.
=begin
I'm a comment!
I don't need any # symbols.
=endGetting User Input
To get input from the user, Ruby uses the gets method. If you want to remove the newline character that is automatically appended, use .chomp.
Example:
print "What is your name?"
name = gets.chompControl Flow
Ruby provides several ways to control the flow of your program:
if: Executes code if a condition is true.
if user_num < 0
puts "Negative number!"
elsif user_num > 0
puts "Positive number!"
else
puts "Zero"
end- Boolean operators:
and,or,not,&&,||,!.
Loops
Ruby offers different types of loops:
- While loop: Repeats an action while a condition is true.
counter = 1
while counter < 11
puts counter
counter += 1
end- For loop: Iterates over a range or collection.
for num in 1...10
puts num
endArrays and Hashes
- Array: An ordered collection of elements, which can be of any type.
arr = [1, 2, 3, "Hello"]
arr.each { |x| puts x }- Hash: A collection of key-value pairs, like a dictionary.
hash = { "name" => "John", "age" => 30 }puts hash["name"] # => John
Methods, Blocks, and Sorting
- Methods: Defined using the
defkeyword and can take arguments.
def greet(name) puts "Hello, #{name}!"
end
- Blocks: Anonymous code that can be passed to methods, like the
.eachiterator.
[1, 2, 3].each { |n| puts n * 2 }
- Sorting: Sort arrays and collections with built-in methods like
.sort.
Refactoring
Refactoring is the process of improving the code's structure without changing its behavior. Ruby provides operators like ||= for conditional assignments and .upto for defining ranges.
x ||= 10 # Sets x to 10 only if x is nil or false
Blocks, Procs, and Lambdas
- Block: A chunk of code passed to a method (e.g.,
.each).
[1, 2, 3].each { |i| puts i * 2 }
- Proc: A saved block that can be reused.
multiply = Proc.new { |n| puts n * 2 }multiply.call(3) # => 6
- Lambda: Similar to a proc, but it checks the number of arguments and returns control to the calling method.
my_lambda = lambda { |n| puts n * 2 }my_lambda.call(4) # => 8
Object-Oriented Programming (OOP)
Ruby is inherently object-oriented, meaning that every piece of data is an object. Classes are blueprints for creating objects, and you can define methods within classes to manipulate those objects.
class Message
@@messages_sent = 0
def initialize(from, to)
@from = from
@to = to
@@messages_sent +=1
end
end
class Email < Message
def initialize(from, to)
super
end
end
my_message = Message.new("hi", "to")