Ruby & Standard Library

Ruby & Standard Library

Enumerable
CSV, JSON, YAML, Base64
Manejo de excepciones
Módulos
Rake

Enumerable (docs)

Array, Hash y Range incluyen Enumerable

arr = [121, 4123, 42, 12, 512]
arr.min           # => 12
arr.max           # => 4132
arr.minmax        # => [12, 4132]
arr.count         # => 5
arr.empty?        # => false
arr.include?(10)  # => false
arr.first         # => 121

Enumerable

Array, Hash y Range incluyen Enumerable

hash = {a: 'uno', b: 'dos', c: 'tres'}

hash.keys         # => [:a, :b, :c]
hash.values       # => ["uno", "dos", "tres"]
hash.count        # => 3
hash.first        # => [:a, "uno"]

Enumerable

Array, Hash y Range incluyen Enumerable

arr.each  {|x| puts x+1}  # (Imprime 122, 4124, 43, 13, 513)
arr.map   {|x| x+10}      # => [131, 4133, 52, 22, 522]
arr.select{|x| x.odd?}    # => [121, 4123]
arr.inject(0) {|acum, obj| acum+obj} # => 4810

map == collect
reduce == inject

Ejemplos

class Trio
  include Enumerable

  def initialize primero, segundo, tercero
    @primero, @segundo, @tercero = primero, segundo, tercero
  end

  def each
    yield @primero
    yield @segundo
    yield @tercero
  end
end

soda_stereo = Trio.new 'Gustavo Cerati', 'Zeta Bosio', 'Charly Alberti'
soda_stereo.each {|integrante| puts integrante}
soda_stereo.include? 'Gustavo Cerati' # => true
soda_stereo.include? 'Charly García'  # => false
class OrdenDeCompra
  include Enumerable

  def add item
    @items ||= []
    @items << item
  end
  def each
    @items.each {|x| yield x}
  end
end

Item = Struct.new(:nombre, :precio)
orden = OrdenDeCompra.new
orden.add(Item.new 'remera', 500)
orden.add(Item.new 'zapatillas', 2500)
orden.add(Item.new 'jean', 2000)
orden.sum{|item| item.precio } # => 5000

CSV (docs)

require 'csv'

csv = CSV.read("beatles.csv")

# [["id", "nombre", "apellido"],
#  ["1", "John", "Lennon"],
#  ["2", "Paul", "McCartney"],
#  ["3", "George", "Harrison"],
#  ["4", "Ringo", "Starr"]]

CSV

csv = CSV.read("beatles.csv", headers: true)

csv.map{|row| row['nombre']}.join(' & ')
# => "John & Paul & George & Ringo"

CSV

csv = CSV.read("beatles.csv",
  headers: true, header_converters: :symbol)
csv.map{|row| row[:nombre]}.join(' & ')
# => "John & Paul & George & Ringo"

CSV

CSV.foreach('beatles.csv',
            headers: true,
            header_converters: :symbol) do |row|
  puts row[:nombre]
end
# John
# Paul
# George
# Ringo

CSV

CSV.foreach('beatles.csv',
            headers: true, header_converters: :symbol).
    map{|row| row[:nombre]}
# => ["John", "Paul", "George", "Ringo"]

CSV - Grabar en un archivo

CSV.open('new_file.csv', 'w') do |file|
  file << %w[id first_name last_name]
  users.each do |user|
    file << [user.id, user.first_name, user.last_name]
  end
end

JSON

require 'json'

# String to Hash
my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] # => "goodbye"

# Hash to String
my_hash = {:hello => "goodbye"}
puts JSON.generate(my_hash) # => "{\"hello\":\"goodbye\"}"

YAML

---
concurrency: 1
queues:
  - default
  - mailers
development:
  logfile: log/sidekiq.log

YAML

require 'yaml'
# Parse a YAML string
YAML.load("--- foo") #=> "foo"

# Emit some YAML
YAML.dump("foo")     # => "--- foo\n...\n"
{ :a => 'b'}.to_yaml  # => "---\n:a: b\n"

Base64

require "base64"

encoded = Base64.encode64('Secret passphrase')
# => "U2VjcmV0IHBhc3NwaHJhc2U=\n"

plain = Base64.decode64(encoded)
# => "Secret passphrase"

Variables predefinidas

  • $_ Ultimo valor leído por gets
  • $& Ultima coincidencia de una expresión regular
  • $0 Nombre del script en ejecución
  • $* Argumentos de línea de comandos con el que se corre el script

English (docs)

  • $_ => $LAST_READ_LINE
  • $& => $MATCH
  • $0 => $PROGRAM_NAME
  • $* => $ARGV
require 'English'
puts $0 == $PROGRAM_NAME
# => true

Manejo de excepciones

raise 'Ocurrió un error! 😱'

# Traceback
#   ...
# RuntimeError (Ocurrió un error! 😱)

Manejo de excepciones

begin
  # ...
  # codigo
  # ...
  raise 'error message'
rescue
  # manejo de errores
end

Manejo de excepciones

begin
  # ... codigo ...
  raise 'error message'
rescue ArgumentError => e  
  puts e.message
rescue RuntimeError => e  
  puts e.backtrace
rescue e # StandardError
  puts e.class.name
end
# BAD!
rescue Exception => e 

Excepciones personalizadas

class PermissionDeniedError < StandardError
  attr_reader :data
  def initialize(message, data)
    # Call the parent's constructor to set the message
    super(message)
    @data = data
  end
end

raise PermissionDeniedError.new("Permission Denied", current_user)

Módulos

  • Módulos como namespaces
  • Composición (mixins)

Módulos como Namespaces

class User
  def hello
    puts "Hola, soy " + self.class.name
  end
end

module MyApp
  class User
    def hello
      puts "Hola, soy " + self.class.name
    end
  end
end

User.new.hello          # => Hola, soy User
MyApp::User.new.hello   # => Hola, soy MyApp::User

Módulos como Mixins

module Commentable
  def comment
    'Esto es un comentario...'
  end
end

class Post
  include Commentable
end

class Quote
  include Commentable
end

Post.new.comment  # => "Esto es un comentario..."
Quote.new.comment # => "Esto es un comentario..."

Rake

# Rakefile
desc "say hello"
task :hello do
  puts "Hello world"
end

task :bye do
  puts "Goodbye"
end

task default: 'hello'
$ rake
Hello world

$ rake bye
Goodbye
namespace :reports do
  desc "run monthly report"
  task :monthly do
    puts "Sending monthly report..."
  end

  desc "generate custom report"
  task :user, [:name, :email] do |task, args|
    puts "work", args[:email]
  end
end
namespace :reports do
  task :first do; end
  task :second do; end

  desc "run monthly report"
  task monthly: [:first, :second] do
  end

  task :user, [:name, :email] do |task, args|
    puts "work", args[:email]
  end
end
$ rake reports:monthly
$ rake reports:user[joaquin,joaquin@gmail.com]
$ rake -T

rake hello                     # say hello
rake reports:monthly           # run monthly report
rake reports:user[name,email]  # generate custom report