Ruby Gotchas

49
RUBY GOTCHAS Algumas surpresas que esperam os novatos

Transcript of Ruby Gotchas

Page 1: Ruby Gotchas

RUBY GOTCHASAlgumas surpresas que esperam os novatos

Page 2: Ruby Gotchas

Sobre mim

• Programador

• Trabalho no Glio

• Novato em Ruby

• @nelson_senna no Twitter

Page 3: Ruby Gotchas

Motivação

Page 4: Ruby Gotchas

– Yukihiro “Matz” Matsumoto

“Ruby is simple in appearance, but is very complex inside, just like our human body.”

Page 5: Ruby Gotchas

Ruby pode ser surpreendente!

Page 6: Ruby Gotchas

Mágica!

Page 7: Ruby Gotchas

No fim tudo é um objeto

Page 8: Ruby Gotchas

Gotcha #1

O que é verdade?

Page 9: Ruby Gotchas

2.3.0 :001 > 0 ? true : false

Page 10: Ruby Gotchas

2.3.0 :001 > 0 ? true : false => true

Page 11: Ruby Gotchas

2.3.0 :001 > ‘’ ? true : false

Page 12: Ruby Gotchas

2.3.0 :001 > ‘’ ? true : false => true

Page 13: Ruby Gotchas

2.3.0 :001 > [] ? true : false

Page 14: Ruby Gotchas

2.3.0 :001 > [] ? true : false => true

Page 15: Ruby Gotchas

2.3.0 :001 > nil ? true : false

Page 16: Ruby Gotchas

2.3.0 :001 > nil ? true : false => false

Page 17: Ruby Gotchas

2.3.0 :001 > false ? true : false

Page 18: Ruby Gotchas

2.3.0 :001 > false ? true : false => false

Page 19: Ruby Gotchas

A pegadinha

Em Ruby só nil e false são considerados “falsey” qualquer outro valor é considerado “truthy”.

Page 20: Ruby Gotchas

Isso é útil?

address = ‘Rua Casa do Ator, 275’ address2 = nil # Famoso complemento

full_address = “Endereço: #{address}\n #{“Complemento: #{address2}” if address2}”

Page 21: Ruby Gotchas

Gotcha #2

(&& ou and) e (|| ou or)?

Page 22: Ruby Gotchas

song = { name: 'Nelson', duration: 300 }

duration = song[:duration]

minutes = duration && duration / 60

puts minutes # imprime 5

Duração em minutos

Page 23: Ruby Gotchas

song = { name: 'Nelson', duration: 300 }

duration = song[:duration]

minutes = duration and duration / 60

puts minutes # imprime 300

Duração em minutos II

Page 24: Ruby Gotchas

O operador = tem maior precedência que o

operador and

Page 25: Ruby Gotchas

O que o Ruby vê

duration = song[:duration]

(minutes = duration) and (duration / 60)

Page 26: Ruby Gotchas

Evitando surpresas

Não use and e or!

Page 27: Ruby Gotchas

Gotcha #3

Constantes podem não ser constantes

Page 28: Ruby Gotchas

Definindo constantes

Ruby considerada constantes “nomes” que começam com letra maiúscula.

Page 29: Ruby Gotchas

Logo

2.3.0 :001 > defined? String => “constant”

Page 30: Ruby Gotchas

Mas…

2.3.0 :001 > String = ‘Nelson’ (irb):2: warning: already initialized constant String (irb):1: warning: previous definition of String was here => “Nelson” 2.3.0 :001 > puts String Nelson => nil

Page 31: Ruby Gotchas

A pegadinha

Em Ruby constantes são referências para objetos e por isso podem ser alteradas.

Page 32: Ruby Gotchas

Evitando surpresas

module CardTypes VISA = ‘visa’.freeze MASTERCARD = ‘mastercard’.freeze end

CardTypes.freeze

Page 33: Ruby Gotchas

Evitando surpresas

# Para arrays precisamos dar freeze # em todos os elementos do mesmo

[‘visa’, ‘mastercard’].map(&:freeze).freeze!

Page 34: Ruby Gotchas

Gotcha #4

Blocks, procs e lambdas

Page 35: Ruby Gotchas

Blocks

10.times { puts ‘A lot of strings’ }

10.times do |number| puts “My number is #{number}” end

Page 36: Ruby Gotchas

Blocksdef get_request(url) uri = URI(url)

response = Net::HTTP.get_response(uri) return response unless block_given?

yield(response) end

get_request(url) do |response| puts response.body end

Page 37: Ruby Gotchas

Blocks

Page 38: Ruby Gotchas

Procs

proc { puts ‘Hello world’ }

Proc.new { puts ‘Hello world’ }

Page 39: Ruby Gotchas

Procs

p = Proc.new do |name| puts “Hello #{name}” end

p.call # imprime “Hello “

Page 40: Ruby Gotchas

A pegadinhadef my_method proc = Proc.new { return “from proc” }

return “from method” end

puts my_method # imprime “from proc”

Page 41: Ruby Gotchas

Lambdas

-> { puts ‘Hello world’ }

lambda { puts ‘Hello world’ }

Page 42: Ruby Gotchas

Lambdas

l = lambda do |name| puts “Hello #{name}” end

l.call # Erro!

Page 43: Ruby Gotchas

A pegadinhadef my_method lam = lambda { return “from proc” }

return “from method” end

puts my_method # imprime “from method”

Page 44: Ruby Gotchas

Resumão!

Page 45: Ruby Gotchas

Extras

Page 46: Ruby Gotchas

Dúvidas?

Page 47: Ruby Gotchas

Referências• http://www.tutorialspoint.com/ruby/ruby_variables.htm

• http://awaxman11.github.io/blog/2013/08/05/what-is-the-difference-between-a-block/

• https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/18-blocks/lessons/64-blocks-procs-lambdas

• http://www.eriktrautman.com/posts/ruby-explained-blocks-procs-and-lambdas-aka-closures

• https://blog.newrelic.com/2015/04/30/weird-ruby-part-4-code-pods/

• http://blog.jayfields.com/2006/12/ruby-constant-values.html

• http://www.informit.com/articles/article.aspx?p=2251208&seqNum=4

• http://rubylearning.com/blog/2010/09/27/almost-everything-is-an-object-and-everything-is-almost-an-object/

Page 48: Ruby Gotchas

Referências• blog.elpassion.com/ruby-gotchas/

• http://phrogz.net/programmingruby/tut_expressions.html

• https://github.com/bbatsov/ruby-style-guide

• https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/

• http://www.tutorialspoint.com/ruby/ruby_operators.htm

• https://blog.engineyard.com/2009/3-ruby-quirks-you-have-to-love

• http://stackoverflow.com/questions/372652/what-are-the-ruby-gotchas-a-newbie-should-be-warned-about

Page 49: Ruby Gotchas

Obrigado