SlideShare a Scribd company logo
1 of 49
Download to read offline
RUBY GOTCHAS
Algumas 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
Blocks
def 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 pegadinha
def 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 pegadinha
def 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

More Related Content

Viewers also liked

Tvi corporate presentation november 2016
Tvi corporate presentation november 2016Tvi corporate presentation november 2016
Tvi corporate presentation november 2016TVI_Pacific
 
Ponuda usluga PoslovnaZnanja.com
Ponuda usluga PoslovnaZnanja.com Ponuda usluga PoslovnaZnanja.com
Ponuda usluga PoslovnaZnanja.com Marko Burazor
 
Trening -Timski rad - Kako unaprediti timski rad? Kako izgraditi tim? (deo pr...
Trening -Timski rad - Kako unaprediti timski rad? Kako izgraditi tim? (deo pr...Trening -Timski rad - Kako unaprediti timski rad? Kako izgraditi tim? (deo pr...
Trening -Timski rad - Kako unaprediti timski rad? Kako izgraditi tim? (deo pr...Marko Burazor
 
Scaling ArangoDB on Mesosphere DCOS
Scaling ArangoDB on Mesosphere DCOSScaling ArangoDB on Mesosphere DCOS
Scaling ArangoDB on Mesosphere DCOSMax Neunhöffer
 
Motori SUS
Motori SUSMotori SUS
Motori SUSNe Cone
 
Tanmay Mudholkar Resume+(SAP)
Tanmay Mudholkar Resume+(SAP)Tanmay Mudholkar Resume+(SAP)
Tanmay Mudholkar Resume+(SAP)Tanmay Mudholkar
 
Inovação Digital 2010
Inovação Digital 2010Inovação Digital 2010
Inovação Digital 2010Fabiano Coura
 
Elektronska regulacija dizel motora
Elektronska regulacija dizel motoraElektronska regulacija dizel motora
Elektronska regulacija dizel motoraigoriv
 

Viewers also liked (10)

Tvi corporate presentation november 2016
Tvi corporate presentation november 2016Tvi corporate presentation november 2016
Tvi corporate presentation november 2016
 
Ponuda usluga PoslovnaZnanja.com
Ponuda usluga PoslovnaZnanja.com Ponuda usluga PoslovnaZnanja.com
Ponuda usluga PoslovnaZnanja.com
 
Trening -Timski rad - Kako unaprediti timski rad? Kako izgraditi tim? (deo pr...
Trening -Timski rad - Kako unaprediti timski rad? Kako izgraditi tim? (deo pr...Trening -Timski rad - Kako unaprediti timski rad? Kako izgraditi tim? (deo pr...
Trening -Timski rad - Kako unaprediti timski rad? Kako izgraditi tim? (deo pr...
 
Scaling ArangoDB on Mesosphere DCOS
Scaling ArangoDB on Mesosphere DCOSScaling ArangoDB on Mesosphere DCOS
Scaling ArangoDB on Mesosphere DCOS
 
OOP: Princípios e Padroes
OOP: Princípios e PadroesOOP: Princípios e Padroes
OOP: Princípios e Padroes
 
Motori SUS
Motori SUSMotori SUS
Motori SUS
 
Tanmay Mudholkar Resume+(SAP)
Tanmay Mudholkar Resume+(SAP)Tanmay Mudholkar Resume+(SAP)
Tanmay Mudholkar Resume+(SAP)
 
Inovação Digital 2010
Inovação Digital 2010Inovação Digital 2010
Inovação Digital 2010
 
Neverbalna komunikacija
Neverbalna komunikacijaNeverbalna komunikacija
Neverbalna komunikacija
 
Elektronska regulacija dizel motora
Elektronska regulacija dizel motoraElektronska regulacija dizel motora
Elektronska regulacija dizel motora
 

More from Nelson Senna do Amaral

More from Nelson Senna do Amaral (9)

Veni vedi vici.
Veni vedi vici.Veni vedi vici.
Veni vedi vici.
 
Pague o aluguel
Pague o aluguelPague o aluguel
Pague o aluguel
 
Dando nome aos códigos
Dando nome aos códigosDando nome aos códigos
Dando nome aos códigos
 
Melhorando seu código com Law of Demeter e Tell don't ask
Melhorando seu código com Law of Demeter e Tell don't askMelhorando seu código com Law of Demeter e Tell don't ask
Melhorando seu código com Law of Demeter e Tell don't ask
 
Domínio: Dividir e conquistar
Domínio: Dividir e conquistarDomínio: Dividir e conquistar
Domínio: Dividir e conquistar
 
Interfaces - Como os objetos deveriam se comportar
Interfaces - Como os objetos deveriam se comportarInterfaces - Como os objetos deveriam se comportar
Interfaces - Como os objetos deveriam se comportar
 
Nossa experiência com TDD
Nossa experiência com TDDNossa experiência com TDD
Nossa experiência com TDD
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Tirando o coelho da cartola: integrando sistemas com RabbitMQ
Tirando o coelho da cartola: integrando sistemas com RabbitMQTirando o coelho da cartola: integrando sistemas com RabbitMQ
Tirando o coelho da cartola: integrando sistemas com RabbitMQ
 

Recently uploaded

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Ruby Gotchas