Ruby Gotchas
-
Upload
nelson-senna-do-amaral -
Category
Technology
-
view
86 -
download
0
Transcript of Ruby Gotchas
RUBY GOTCHASAlgumas surpresas que esperam os novatos
Sobre mim
• Programador
• Trabalho no Glio
• Novato em Ruby
• @nelson_senna no Twitter
Motivação
– Yukihiro “Matz” Matsumoto
“Ruby is simple in appearance, but is very complex inside, just like our human body.”
Ruby pode ser surpreendente!
Mágica!
No fim tudo é um objeto
Gotcha #1
O que é verdade?
2.3.0 :001 > 0 ? true : false
2.3.0 :001 > 0 ? true : false => true
2.3.0 :001 > ‘’ ? true : false
2.3.0 :001 > ‘’ ? true : false => true
2.3.0 :001 > [] ? true : false
2.3.0 :001 > [] ? true : false => true
2.3.0 :001 > nil ? true : false
2.3.0 :001 > nil ? true : false => false
2.3.0 :001 > false ? true : false
2.3.0 :001 > false ? true : false => false
A pegadinha
Em Ruby só nil e false são considerados “falsey” qualquer outro valor é considerado “truthy”.
Isso é útil?
address = ‘Rua Casa do Ator, 275’ address2 = nil # Famoso complemento
full_address = “Endereço: #{address}\n #{“Complemento: #{address2}” if address2}”
Gotcha #2
(&& ou and) e (|| ou or)?
song = { name: 'Nelson', duration: 300 }
duration = song[:duration]
minutes = duration && duration / 60
puts minutes # imprime 5
Duração em minutos
song = { name: 'Nelson', duration: 300 }
duration = song[:duration]
minutes = duration and duration / 60
puts minutes # imprime 300
Duração em minutos II
O operador = tem maior precedência que o
operador and
O que o Ruby vê
duration = song[:duration]
(minutes = duration) and (duration / 60)
Evitando surpresas
Não use and e or!
Gotcha #3
Constantes podem não ser constantes
Definindo constantes
Ruby considerada constantes “nomes” que começam com letra maiúscula.
Logo
2.3.0 :001 > defined? String => “constant”
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
A pegadinha
Em Ruby constantes são referências para objetos e por isso podem ser alteradas.
Evitando surpresas
module CardTypes VISA = ‘visa’.freeze MASTERCARD = ‘mastercard’.freeze end
CardTypes.freeze
Evitando surpresas
# Para arrays precisamos dar freeze # em todos os elementos do mesmo
[‘visa’, ‘mastercard’].map(&:freeze).freeze!
Gotcha #4
Blocks, procs e lambdas
Blocks
10.times { puts ‘A lot of strings’ }
10.times do |number| puts “My number is #{number}” end
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
Blocks
Procs
proc { puts ‘Hello world’ }
Proc.new { puts ‘Hello world’ }
Procs
p = Proc.new do |name| puts “Hello #{name}” end
p.call # imprime “Hello “
A pegadinhadef my_method proc = Proc.new { return “from proc” }
return “from method” end
puts my_method # imprime “from proc”
Lambdas
-> { puts ‘Hello world’ }
lambda { puts ‘Hello world’ }
Lambdas
l = lambda do |name| puts “Hello #{name}” end
l.call # Erro!
A pegadinhadef my_method lam = lambda { return “from proc” }
return “from method” end
puts my_method # imprime “from method”
Resumão!
Extras
Dúvidas?
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/
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
Obrigado