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.5k
O que mudou no Rails 5
fnando
3
530
Porque usar PostgreSQL (Se você ainda não o faz)
fnando
25
2.9k
Criando aplicações web mais seguras
fnando
4
630
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
920
Other Decks in Technology
See All in Technology
株式会社EventHub・エンジニア採用資料
eventhub
0
4.3k
RSNA2024振り返り
nanachi
0
580
CZII - CryoET Object Identification 参加振り返り・解法共有
tattaka
0
370
関東Kaggler会LT: 人狼コンペとLLM量子化について
nejumi
3
590
OpenID BizDay#17 KYC WG活動報告(法人) / 20250219-BizDay17-KYC-legalidentity
oidfj
0
250
【Developers Summit 2025】プロダクトエンジニアから学ぶ、 ユーザーにより高い価値を届ける技術
niwatakeru
2
1.4k
一度 Expo の採用を断念したけど、 再度 Expo の導入を検討している話
ichiki1023
1
170
滅・サービスクラス🔥 / Destruction Service Class
sinsoku
6
1.6k
インフラをつくるとはどういうことなのか、 あるいはPlatform Engineeringについて
nwiizo
5
2.6k
(機械学習システムでも) SLO から始める信頼性構築 - ゆる SRE#9 2025/02/21
daigo0927
0
120
なぜ私は自分が使わないサービスを作るのか? / Why would I create a service that I would not use?
aiandrox
0
740
室長と気ままに学ぶマイクロソフトのビジネスアプリケーションとビジネスプロセス
ryoheig0405
0
370
Featured
See All Featured
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
21
2.5k
Documentation Writing (for coders)
carmenintech
67
4.6k
How to Think Like a Performance Engineer
csswizardry
22
1.3k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
28
9.3k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
366
25k
The Straight Up "How To Draw Better" Workshop
denniskardys
232
140k
Faster Mobile Websites
deanohume
306
31k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
251
21k
Navigating Team Friction
lara
183
15k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
356
29k
The Art of Programming - Codeland 2020
erikaheidi
53
13k
Reflections from 52 weeks, 52 projects
jeffersonlam
348
20k
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!