Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby: Dicas & Truques

Ruby: Dicas & Truques

Nando Vieira

July 07, 2012
Tweet

More Decks by Nando Vieira

Other Decks in Technology

Transcript

  1. class SimpleLogger def initialize(storage = []) unless storage.is_a?(Array) raise "you

    need to pass an array" end @storage = storage end def log(message) @storage << message end end
  2. class SimpleLogger def initialize(storage = []) @storage = storage end

    def log(message) @storage << message end end
  3. O Ruby leva o Duck Typing por toda a linguagem,

    usando-o como protocolo de coersão.
  4. sum_proc = proc do |n1, n2| n1 + n2 end

    sum_lambda = lambda do |n1, n2| n1 + n2 end
  5. sum_proc.call #=> NoMethodError: undefined #=> method `+' for nil:NilClass sum_lambda.call

    #=> ArgumentError: wrong number #=> of arguments (0 for 2)
  6. def proc_return proc { return "returning from proc" }.call "proc

    has finished" end puts proc_return #=> returning from proc
  7. def lambda_return lambda { return "lambda: exiting method" }.call "lambda

    has finished" end puts lambda_return #=> lambda has finished
  8. lambda { return "hello" }.call #=> hello proc { return

    "hello" }.call #=> LocalJumpError: unexpected return
  9. case object when multiple_of_3 "is multiple of 3" when Array

    "is a array" when /@/ "contains at-sign" else "couldn't understand" end
  10. class Hellobits alias_method :original_cool, :cool def cool # do something

    before original_cool # do something after end end
  11. class Hellobits cool_method = instance_method(:cool) define_method :cool do # do

    something before cool_method.bind(self).call # do something after end end