Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Ruby: Dicas & Truques
Search
Nando Vieira
July 07, 2012
Technology
20
1.3k
Ruby: Dicas & Truques
Nando Vieira
July 07, 2012
Tweet
Share
More Decks by Nando Vieira
See All by Nando Vieira
Permanecendo Relevante
fnando
9
1.4k
O que mudou no Rails 5
fnando
3
530
Porque usar PostgreSQL (Se você ainda não o faz)
fnando
25
2.8k
Criando aplicações web mais seguras
fnando
4
610
Criando aplicações mais fáceis de manter com Ruby on Rails
fnando
35
2.1k
Conhecendo Variants do Rails 4.1
fnando
11
550
JavaScript Funcional
fnando
36
1.7k
Segurança em Aplicações Web
fnando
31
3k
Segurança no Rails
fnando
20
910
Other Decks in Technology
See All in Technology
The Role of Developer Relations in AI Product Success.
giftojabu1
0
120
隣接領域をBeyondするFinatextのエンジニア組織設計 / beyond-engineering-areas
stajima
1
270
Lexical Analysis
shigashiyama
1
150
AWS Lambda のトラブルシュートをしていて思うこと
kazzpapa3
2
170
ExaDB-D dbaascli で出来ること
oracle4engineer
PRO
0
3.8k
10XにおけるData Contractの導入について: Data Contract事例共有会
10xinc
6
620
Platform Engineering for Software Developers and Architects
syntasso
1
520
Terraform未経験の御様に対してどの ように導⼊を進めていったか
tkikuchi
2
430
誰も全体を知らない ~ ロールの垣根を超えて引き上げる開発生産性 / Boosting Development Productivity Across Roles
kakehashi
1
220
スクラム成熟度セルフチェックツールを作って得た学びとその活用法
coincheck_recruit
1
140
OCI Vault 概要
oracle4engineer
PRO
0
9.7k
Why does continuous profiling matter to developers? #appdevelopercon
salaboy
0
190
Featured
See All Featured
Music & Morning Musume
bryan
46
6.2k
Building Applications with DynamoDB
mza
90
6.1k
How To Stay Up To Date on Web Technology
chriscoyier
788
250k
The Invisible Side of Design
smashingmag
298
50k
Designing the Hi-DPI Web
ddemaree
280
34k
[RailsConf 2023] Rails as a piece of cake
palkan
52
4.9k
Code Review Best Practice
trishagee
64
17k
Become a Pro
speakerdeck
PRO
25
5k
It's Worth the Effort
3n
183
27k
Raft: Consensus for Rubyists
vanstee
136
6.6k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
Facilitating Awesome Meetings
lara
50
6.1k
Transcript
DICAS & TRUQUES RUBY Nando Vieira hellobits.com
@fnando
None
None
None
DICAS E TRUQUES CURIOSOS QUE PODEM SER ÚTEIS (OU NÃO)
NO DIA-A-DIA.
None
No Ruby, tudo é objeto (ou quase tudo).
Classes, módulos, números, strings, arrays, intervalos, símbolos, métodos, blocos, procs,
nil, booleanos, hashes, expressões regulares.
O Ruby possui classes abertas que podem ser modi cadas
a qualquer momento.
O Ruby é extremamente exível.
O Ruby é muito mais difícil do que as pessoas
assumem.
DUCK TYPING, PROTOCOLOS E CONTRATOS
O Duck Typing permite estabelecer interfaces com um contrato informal.
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
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
@storage.<<(value)
File#<< String#<< Array#<< CSV#<< Set#<< IO#<< StringIO#<< Queue#<<
class SimpleLogger def initialize(storage = []) @storage = storage end
def log(message) @storage << message end end
logger = SimpleLogger.new(nil) logger.log("Hello") #=> NoMethodError: undefined #=> method `<<'
for nil:NilClass
O Ruby leva o Duck Typing por toda a linguagem,
usando-o como protocolo de coersão.
#to_a #to_ary #to_d #to_f #to_i #to_proc #to_s
#to_proc
people = Person.all names = people.map do |person| person.name end
people = Person.all names = people.map(&:name)
&Na assinatura do método, converte bloco em Proc.
&Na chamada do método, converte Proc em bloco.
method(&object)
object.to_proc
people.map(&:name)
:name.to_proc #=> #<Proc:0x871cd04>
:name .to_proc .call(people.first)
class Symbol def to_proc proc do |target| target.public_send(self) end end
end
PROCS & LAMBDAS
sum_proc = proc do |n1, n2| n1 + n2 end
sum_lambda = lambda do |n1, n2| n1 + n2 end
sum_proc.class #=> Proc sum_lambda.class #=> Proc
sum_proc.lambda? #=> false sum_lambda.lambda? #=> true
sum_proc.parameters #=> [[:opt, :n1], [:opt, :n2]] sum_lambda.parameters #=> [[:req, :n1],
[:req, :n2]]
Os parâmetros de um lambda são obrigatórios por padrão.
sum_proc.call #=> NoMethodError: undefined #=> method `+' for nil:NilClass sum_lambda.call
#=> ArgumentError: wrong number #=> of arguments (0 for 2)
def proc_return proc { return "returning from proc" }.call "proc
has finished" end puts proc_return #=> returning from proc
O retorno da proc, na verdade, faz com que o
método pare de executar.
def lambda_return lambda { return "lambda: exiting method" }.call "lambda
has finished" end puts lambda_return #=> lambda has finished
O retorno do lambda é auto- contido e não afeta
o método.
O retorno de procs pode, inclusive, lançar exceções.
lambda { return "hello" }.call #=> hello proc { return
"hello" }.call #=> LocalJumpError: unexpected return
proc { next "hello" this_wont_be_executed }.call
CALLABLE OBJECTS
hello = proc do |name| puts "hello, #{name}!" end
hello.call("John")
hello["John"]
hello.("John")
hello === "John"
object = 9 multiple_of_3 = proc do |n| n.modulo(3).zero? end
case object when multiple_of_3 "is multiple of 3" when Array
"is a array" when /@/ "contains at-sign" else "couldn't understand" end
Proc#=== Regexp#=== Module#===
Array === [] #=> true multiple_of_3 === 9 #=> true
/@/ === "
[email protected]
" #=> true
Object#method Module#instance_method
Métodos não são objetos de primeira classe.
Estendendo métodos sem ter que criar uma nova classe.
class Hellobits def cool # do something end end
class Hellobits alias_method :original_cool, :cool def cool # do something
before original_cool # do something after end end
class Hellobits cool_method = instance_method(:cool) define_method :cool do # do
something before cool_method.bind(self).call # do something after end end
SPLATTING
*args
class Module def attr_dsl(*args) args.each do |arg| # do something
end end end
class Settings names = %w[path size locale] attr_dsl *names end
def coords(*) # do something -23.598737, -46.674685 end latitude, longitude
= coords
a, b, c, d = [1, 2, 3, 4]
a, b, c, d = 1, 2, 3, 4
a, b, *c = 1, 2, 3, 4 #=> a=1,
b=2, c=[3,4]
a, *b, c = 1, 2, 3, 4 #=> a=1,
b=[2,3], c=4
numbers = [1, 2, 3] more_numbers = [*numbers, 4, 5,
6] #=> [1, 2, 3, 4, 5, 6]
(1..10).to_a.sample [*1..10].sample
date = "2012-07-10" regex = /(\d+)-(\d+)-(\d+)/ _, year, month, day
= *date.match(regex)
class Sample def to_a [1, 2, 3] end end a,
b, c = *Sample.new
MAIS SOBRE ATRIBUIÇÕES
path = nil if !path path = "/some/default/path" end
path = nil path = "/some/path" unless path
path = nil path ||= "/some/path"
variable || variable = expr
html = nil if html html << "<p>Hello</p>" end
html = nil html << "<p>Hello</p>" if html
html = nil html &&= html << "<p>Hello</p>"
variable && variable = expr
DE ONDE VEM ESSE MÉTODO
user = User.new user.methods #=> [:name, :age, ...]
user.method(:name)
Method#arity Method#name Method#owner Method#parameters Method#source_location
user.method(:name) .source_location #=> ["/tmp/user.rb", 2]
EXPRESSÕES REGULARES
person = "John <
[email protected]
>" regex = /(.*?) <(.*?)>/ _, name,
email = *person.match(regex)
person[/(.*?) <(.*?)>/, 1] person[/(.*?) <(.*?)>/, 2]
person .match(/(?<name>.*?) <(?<email>.*?)>/)
match.names #=> ["name", "email"] match.captures #=> ["John Doe", "
[email protected]
"] match[:name]
#=> "John Doe" match[:email] #=> "
[email protected]
"
ENUMERATORS
names.each(&block) names.each_with_index(&block)
names.each_with_index do |name, index| puts "#{index + 10}. #{name}" end
names .each .with_index(10) do |name, index| puts "#{index}. #{name}" end
names .sort .uniq .each .with_index(10, &block)
HASHES & ENUMERATORS
hash.each do |key, value| # do something end
hash .each .with_index(10) do |pair, index| name, value = pair
# do something end
hash .each .with_index(10) do |(name, value), index| # do something
end
SYMBOLS
:name
:"full name"
:"hello #{name}"
E PARA FINALIZAR...
O Ruby possui uma série de truques que podem ajudar
bastante.
Mais do que saber usar, você precisa saber quando usar.
Sintaxes exotéricas serão mais difíceis de entender.
Conheça Ruby. Todo o resto vem de graça.
OBRIGADO!