SlideShare a Scribd company logo
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 2016
TVI_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 DCOS
Max Neunhöffer
 
OOP: Princípios e Padroes
OOP: Princípios e PadroesOOP: Princípios e Padroes
OOP: Princípios e Padroes
Nelson Senna do Amaral
 
Motori SUS
Motori SUSMotori SUS
Motori SUS
Ne 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 2010
Fabiano Coura
 
Neverbalna komunikacija
Neverbalna komunikacijaNeverbalna komunikacija
Neverbalna komunikacija
Lucija Šantić
 
Elektronska regulacija dizel motora
Elektronska regulacija dizel motoraElektronska regulacija dizel motora
Elektronska regulacija dizel motora
igoriv
 

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

Veni vedi vici.
Veni vedi vici.Veni vedi vici.
Veni vedi vici.
Nelson Senna do Amaral
 
Pague o aluguel
Pague o aluguelPague o aluguel
Pague o aluguel
Nelson Senna do Amaral
 
Dando nome aos códigos
Dando nome aos códigosDando nome aos códigos
Dando nome aos códigos
Nelson Senna do Amaral
 
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
Nelson Senna do Amaral
 
Domínio: Dividir e conquistar
Domínio: Dividir e conquistarDomínio: Dividir e conquistar
Domínio: Dividir e conquistar
Nelson Senna do Amaral
 
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
Nelson Senna do Amaral
 
Nossa experiência com TDD
Nossa experiência com TDDNossa experiência com TDD
Nossa experiência com TDD
Nelson Senna do Amaral
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Nelson Senna do Amaral
 
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
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

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 

Recently uploaded (20)

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 

Ruby Gotchas