Skip to content

Instantly share code, notes, and snippets.

@mitio
Last active September 5, 2018 06:40
Show Gist options
  • Save mitio/d70ad8ff5775b46b2355f9b3c4fcf209 to your computer and use it in GitHub Desktop.
Save mitio/d70ad8ff5775b46b2355f9b3c4fcf209 to your computer and use it in GitHub Desktop.
Ruby basics workshop #1

Ruby workshop agenda

  1. Data types
  2. Basic syntax
  3. Objects, data types/structures (basic)
  4. Ecosystem – gems, docs; C extensions
  5. Blocks & loops

Advanced:

  • parallel assignment
  • blocks & procs & lambdas
  • classes, modules, inheritance
  • threads & GVL

Tips for learning

  • reading code
  • writing code
foo = 42
bar = "baz"
class Fixnum
def +(other)
if other == 4
100
elsif other == 5
50
end
case other
when 4 then 7100
when 5 then 750
else 71
end
end
end
# receiver.method_name(param, param2, param3)
# puts bar.size()
puts "weirdness\n", 4.+(4).inspect, (3 + 3).inspect
# def trice
# yield
# yield
# yield
# end
# trice { puts 'first' }
# puts '=' * 20
# trice do
# puts 'second'
# end
# trice {}
def calculate
yield :info, "Starting..."
# oooo....
if rand(10) < 4
yield :error, "Failed with an error!"
else
yield :info, "Success."
end
yield(:info, "Finished.")
end
require 'logger'
logger = Logger.new(STDOUT)
calculate do |severity, message|
# logger.public_send(severity, message)
case severity
when :info then logger.info(message)
when :error then logger.error(message)
end
end
calculate {}
# ---------------
def apply_taxes(amount)
amount + yield(amount)
end
puts apply_taxes(100) { |amount| amount * 0.2 }
x = [1, 2, 5, 12, 'baba']
# Enumerable
result = x.each { |item| puts "item: #{item}" }
puts "=> #{result.inspect}"
result = x.map { |item| item * 2 }
puts "=> #{result.inspect}"
x = [1, 2, 5, 12, 'baba']
def iterate_over(enumerable)
length = enumerable.length
i = 0
while i < length
current_item = enumerable[i]
i = i + 1
yield current_item
end
end
def transform(enumerable)
length = enumerable.length
i = 0
result = []
while i < length
current_item = enumerable[i]
i = i + 1
result << yield(current_item)
end
result
end
transformed = transform(x) do |item|
# puts item
item * item if item.is_a? Fixnum
end
puts transformed.inspect
# scope gates: def, class, module
class InfraTeam
foo = 42
def awesome(name = 'BBB')
puts "Hello #{name}!"
end
def InfraTeam.awesome
puts 'We are awesome!'
end
def self.awesome2
InfraTeam.awesome
end
class << self
def awesome3
awesome
end
end
end
# InfraTeam.send(:private, :awesome)
name = "Bam" * 2
name.upcase!
InfraTeam.new.awesome
InfraTeam.awesome
InfraTeam.awesome2
InfraTeam.awesome3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment