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
速くて安いWebサイトを作る
nishiharatsubasa
10
13k
Amazon S3 Tablesと外部分析基盤連携について / Amazon S3 Tables and External Data Analytics Platform
nttcom
0
140
次世代KYC活動報告 / 20250219-BizDay17-KYC-nextgen
oidfj
0
260
TAMとre:Capセキュリティ編 〜拡張脅威検出デモを添えて〜
fujiihda
2
250
Nekko Cloud、 これまでとこれから ~学生サークルが作る、 小さなクラウド
logica0419
2
970
レビューを増やしつつ 高評価維持するテクニック
tsuzuki817
1
730
PHPで印刷所に入稿できる名札データを作る / Generating Print-Ready Name Tag Data with PHP
tomzoh
0
110
Raycast AI APIを使ってちょっと便利な拡張機能を作ってみた / created-a-handy-extension-using-the-raycast-ai-api
kawamataryo
0
100
【Developers Summit 2025】プロダクトエンジニアから学ぶ、 ユーザーにより高い価値を届ける技術
niwatakeru
2
1.4k
Tech Blogを書きやすい環境づくり
lycorptech_jp
PRO
1
240
あれは良かった、あれは苦労したB2B2C型SaaSの新規開発におけるCloud Spanner
hirohito1108
2
610
データ資産をシームレスに伝達するためのイベント駆動型アーキテクチャ
kakehashi
PRO
2
540
Featured
See All Featured
Git: the NoSQL Database
bkeepers
PRO
427
64k
Docker and Python
trallard
44
3.3k
Why Our Code Smells
bkeepers
PRO
336
57k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
356
29k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
30
2.2k
Imperfection Machines: The Place of Print at Facebook
scottboms
267
13k
Visualization
eitanlees
146
15k
Reflections from 52 weeks, 52 projects
jeffersonlam
348
20k
Optimizing for Happiness
mojombo
376
70k
Unsuck your backbone
ammeep
669
57k
How To Stay Up To Date on Web Technology
chriscoyier
790
250k
Building Flexible Design Systems
yeseniaperezcruz
328
38k
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!