Ruby Basics II

Objetives

Arrays

# Create Arrays

empty = []
numbers = [1, 2, 3, 4, 5]
words = ["See", "Spot", "run"]
mixed = ["hello", 5, true, 3.0]
# Every item in the array is indexale

collection = [
  1,
  "Codeable",
  2.0,
  true
]


puts collection[0]
collection[3] = false
# Nesting / Multidimensional arrays[arrays[arrays]]

nested_array = [
  [0,1,2,3],
  ["Diego", "André", "Paulo"],
  [false, true]
]
 
puts nested_array[1] 
# => ["Diego", "André", "Paulo"]
 
puts nested_array[2][0] 
# => false
# Array operators

first_array = [
  0,
  1,
  2
]
 
second_array = [
  2,
  3,
  4
]
 
puts first_array + second_array
puts first_array - second_array
puts first_array & second_array 
first_array * 3
# Everything is an object!

array = [
  0,
  nil,
  "Codeable",
  false,
  nil,
]
 
puts array.first
puts array.last
puts array.length
puts array.sort
puts array.compact
puts array.rotate
# Each in Array

words = [
 "See", 
 "Spot", 
 "run"
]
 
words.each { |word | puts word }

words.each_with_index { |word, index| puts "#{index} => #{word}" }

Symbols


"a symbol".object_id
:a_symbol.object_id

Hashes

# Create with literal notation and retrieve 

car = {
  :wheels => 4,
  :brand => "Toyota",
  :color? => "red"
}
 
puts car["color?"]
# Create with new method and assign

car = Hash.new
car["color?"] = "red"
 
puts car
# Useful methods

dictionary = {
  "course" => "Codeable", 
  "module" => "ruby", 
  "lesson" => "fundamentals II"
}
 
dictionary.merge({ "TE" => "André" })
dictionary.keys
dictionary.values
dictionary.length
dictionary.size
# Map in Hash

modules = {
  "ruby" => 5,
  "rails" => 4,
  "react" => 5
}
 
modules.map do |language, weeks|
  "The #{language} module has #{weeks} weeks."
end

Ruby Basics II

By Paulo Tijero

Ruby Basics II

  • 143