Introduction to Ruby
Who am I?
Installation
Conventions
- File/Directory lower case
- Identation: two spaces
- _ for variable name
- One quote for Strings
- @variable ||= "default value"
- && (and)
Features
- Case sensitive
Comments
- Anything followed by a #
- For large blocks of code, anything between =begin and =end
Example 1
# p001rubyhelloworld.rb
=begin
Printing a hello world in ruby.
Testing a block comment.
=end
hello_world = 'Hello World, Ruby!'
puts hello_world
Nil and false
- Everything is true, except for nil and false.
- Zero, null character, [] are true.
Everything is an object
- String
- Numbers
Example 2
# p002rubyobject.rb
#everything is an object in ruby
puts 'I am Batman'.class
puts 29.to_s
puts 'Why so serious ' + 3.to_s
Strings
- Objects
- to_s
- s * 9
- <<
- Interpolation/Placeholder
Example 3
# p003rubystrings.rb
# strings are objects
puts 'But you dont\'t know fear half as well as it knows you.'.class
# how to convert to a string and print many times
number = 3
puts number.to_s * 4
# append to a string
batman = 'And Batman?'
batman << 'I\'m not sure what scares him.
Maybe hes driven by his fears..'
puts batman
# String interpolation
placeholder = 'use string interpolation'
puts "I can #{placeholder} when using double quoted strings"
Numbers
Example 4
# p004rubynumbers.rb
=begin
Ruby Numbers
Usual operators
+ addition
- subtraction
* multiplication
/ division
=end
puts 1 + 2
puts 2 * 3
# Integer division
# When you do arithmetic with integers, you'll get integer answers
puts 3 / 2
puts 10 - 11
puts 1.5 / 2.6
Methods
- Returns the value of the last line
- If they act as queries, are often named with ?
- To modify the receiver use !
Example 5
# p005mymethods.rb
def batman
'Batman'
end
#use the method
puts batman
quote = 'Why so serious?'
# Method that does not modify the variable
def updateQuoteFalse quote
quote = quote.reverse
end
# Method that does modify the variable
def updateQuoteTrue quote
quote = quote.reverse!
end
updateQuoteFalse(quote)
puts quote
updateQuoteTrue(quote)
puts quote
Symbols
- Objects
- Immutable, reusable constants.
- Meaningful values
Example 6
# p006rubysymbols.rb
puts :danger.class
status = :danger
puts status == :danger
puts status == 'danger'
puts status == :safe
Arrays
- Objects
- reverse
- <<
- push
- include?
Example 7
# p007rubyarray.rb
a = ['Harley Quinn', 30, true]
a.reverse!
a << 'Joker'
puts "Playing with #{a}"
puts a.include?('Joker')
Unless and If
- unless with else is confusing
- inline conditionals
- conditional assignment
Example 8
#p008rubyconditional.rb
character = 'Batman'
# Bad code
if character != nil
puts 'Bad'
end
# Good code
if character
puts 'Good'
end
# Conditional assignment
character ||= 'Joker'
puts character
villain ||= 'Joker'
puts villain
villain = 'Harley Quinn'
# Inline conditionals and unless
puts 'There is no villain' unless villain
puts villain if villain
Hash
- Primary dictionary with key/value pairs
- Denoted with curly braces
Example 9
#p009rubyhash.rb
# Bad code. Long parameter list
def villain(name, firstAppearance = nil, age = nil, quote = nil)
def hero(name, options{}){
character = hero.new
character.firstAppearance = options[:firstAppearance]
character.age = options[:age]
character.quote = options[:quote]
}
hero('Batman',
:firstAppearance => 1938,
:age => 36
:quote => 'I am Batman'
) #keys show meaning
Class
- attr_accessor
- self
- re-open
Example 10
#p010rubyclass.rb
class Character
attr_accessor :name, :firstAppearance
def initialize(name, firstAppearance)
@name = name
@firstAppearance = firstAppearance
end
end
batman = Character.new('Batman', 1938)
# Re-opening a class
class Character
def to_s
"I am #{name} and my first appearance was in #{firstAppearance}"
end
end
puts batman.to_s
Case
- ranges
- when/then
Example 11
#p011rubycase.rb
result = 29
score = case result
when 0..9
nil
when 10..29
"great"
else
"amazing"
end
score_type = case result
when 29 then :great
end
puts score
puts score_type
Exception
Example 12
#p012rubyexception.rb
# exception handling:
begin
# code here that might raise an exception
raise NoMemoryError, 'You ran out of memory.'
rescue NoMemoryError => exception_variable
puts 'NoMemoryError was raised', exception_variable
rescue RuntimeError => other_exception_variable
puts 'RuntimeError was raised now'
else
puts 'This runs if no exceptions were thrown at all'
ensure
puts 'This code always runs no matter what'
end
Useful links to learn more!
Thanks for your attention!
Any questions?
Introduction to Ruby
By Carolina Pascale Campos
Introduction to Ruby
- 800