Introduction To Ruby - CA
Introduction To Ruby - CA
Introduction to Ruby
Ruby Variables
In Ruby, a variable is a place to store values of almost any
type including Integer, Boolean, String, Array, and Hashes. myVar = 48
Each variable has its own name which cannot begin with a
capital letter or a number and we use the equal sign for
assigning a value to that variable.
The variable declaration does not require that you
mention a speci c data type.
The following program declares myvar variable and
assigns the value 48 .
# Float value
y = 1.2
Arithmetic operations in Ruby
In Ruby, we can use arithmetic operators to evaluate
mathematical expressions. The most common Ruby print 1+3
arithmetic operators are addition (+), subtraction (-), # Addition: output 4
division(/), multiplication(*), exponentiation(**) and
modulo(%).
print 1-2
# Subtraction: output -1
print 9/3
# Division: output 3
print 2*3
# Multiplication: output 6
print 2**3
# Exponentiation: output 8
print 16%9
# Modulo: output 7
Strings in Ruby
Strings in Ruby are a sequence of characters enclosed by
single quotation marks (‘’) or double quotation marks (“”). # String 1
s1 = 'I am a single string!'
# String 2
s2 = "I am a double string!"
Boolean Data Types in Ruby
In Ruby, in order to represent values of truth about
speci c statements, we use Boolean variables. Boolean # Boolean true variable
variables values are either true or false . year2019 = true
if Statement in Ruby
An if statement in Ruby evaluates an expression,
number = 10
which returns either true or false . If the
if number == 10
expression is true , Ruby executes the code block that
puts "Your condition was true!"
follows the if whereas if the expression is false ,
end
Ruby returns nil.
In this example, the string "Your condition
was true!" will print because the condition
number == 10 is true.
# Output:
# 1
# 3
# 5
# 7
# 9
Ruby while Loop
Putting a block of code in a while loop in Ruby will
cause the code to repeatedly run the code as long as its
condition is true .
If the block of code doesn’t have a way for the condition
to be changed to false , the while loop will
continue forever and cause an error.
# Output:
# Codecademy
# Codecademy
# Codecademy
# Codecademy
# Codecademy
Ruby Range
In ruby, a sequence of integers can be demonstrated by a
range. The range can be divided into an inclusive range
where the last integer in the sequence is included and an
exclusive range where the last integer is excluded.
Ruby loop
A loop method can be used to run a block of code
repeatedly in Ruby. Either use curly braces ( {} ) or the
do / end keyword combination to wrap the block the
code that will be looped.
empty = []
#An empty array
Ruby Hash
In Ruby, a hash is a collection of key-value pairs.
A hash is denoted by a set of curly braces ( {} ) which profile = {
contains key-value pairs separated by commas. Each "name" => "Magnus",
value is assigned to a key using a hash rocket ( => ). "profession" => "chess player"
Calling the hash followed by a key name within brackets "ranking" => 1,
grabs the value associated with that key. "grandmaster?" => true
}
salary = {
"starting" => 40000
}
salary["mid-level"] = 60000
polygons = {
"pentagon" => 5,
"hexagon" => 6,
"nonagon" => 9
}
puts 3 <=> 3 # 0
extra_curriculars("chess club",
"gymnastics", "anime club", "library
services")
#Output
#After school, I'm involved with chess
club
#After school, I'm involved with
gymnastics
#After school, I'm involved with anime
club
#After school, I'm involved with
library services
generous_tip(100) # 25
Ruby Block
In Ruby, a block is a section of code de ned within the
keywords do and end or with curly braces {} . 2.times do
This is usually preceded by an integer followed by puts "I'm a code block!"
.times to indicate how many times the code is to be end
executed.
#Output
#I'm a code block!
#I'm a code block!
#Output
#"So am I!"
#"So am I!"
#"So am I!"
Cheatsheets / Learn Ruby
my_progress = {
program: "Codecademy",
language: "Ruby",
enthusiastic?: true
}
#Key symbols and their values can also
be defined with the colon (:) at the
end of the symbol followed by its
value.
Ruby .select Method
In Ruby, the .select method can be used to grab
speci c values from a hash that meet a certain criteria. olympic_trials = {
Sally: 9.58,
John: 9.69,
Bob: 14.91
}
Refactoring
Ruby Case Statement
In Ruby, a case statement is a more concise
tv_show = "Bob's Burgers"
alternative to an if/else statement that contains
many conditions.
case tv_show
when "Archer"
puts "I don't like the voice of
Archer."
when "Bob's Burgers"
puts "I love the voice of Bob
Belcher."
else
puts "I don't know who voices this
cartoon."
end
puts "A".respond_to?(:next)
# => true
# Here, however, the following Ruby
code will return true since .next can
be called on a String object. Calling
.next on the letter “A” would return
the letter “”.
puts boyfriend
# => "Jimmy Jr."
product(5, 4)
# => 20
#In this example, Ruby evaluates the
product method and returns 20 even
though the return keyword was omitted.
Cheatsheets / Learn Ruby
puts proc_demo_method
# Output
# Only I print!
def lambda_demo_method
lambda_demo = lambda { return "Will
I print?" }
lambda_demo.call
"Sorry - it's me that's printed."
end
puts lambda_demo_method
# Output
# Sorry - it's me that's printed.
[2, 4, 6].collect!(&square)
# When passing a proc to a method, an
& is used to convert the proc into
a block.
def self.children_added
return @@children
end
end
spain_backpacking = Trip.new(14,
800.00)
carnival = Cruise.new(7, 2400.00)
Ruby Class
A Ruby class is used to organize and model objects with
similar attributes and methods. class NewClass
# code for this class
end
top_student = Student.new("Jyothi")
puts top_student.name # => Jyothi
#In classes with attr_reader, instance
variables can be accessed using
. notation
puts Math::PI
# => 3.141592653589793
module MyPizza
FAVE_TOPPING = "Buffalo Chicken"
end
#In this example, myPizza is a module
that holds a constant, FAVE_TOPPING,
set equal to the string, Buffalo
Chicken.