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.9k
Criando aplicações web mais seguras
fnando
4
620
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
Oracle Cloudの生成AIサービスって実際どこまで使えるの? エンジニア目線で試してみた
minorun365
PRO
4
280
KubeCon NA 2024 Recap: How to Move from Ingress to Gateway API with Minimal Hassle
ysakotch
0
200
多領域インシデントマネジメントへの挑戦:ハードウェアとソフトウェアの融合が生む課題/Challenge to multidisciplinary incident management: Issues created by the fusion of hardware and software
bitkey
PRO
2
100
1等無人航空機操縦士一発試験 合格までの道のり ドローンミートアップ@大阪 2024/12/18
excdinc
0
160
Jetpack Composeで始めるServer Cache State
ogaclejapan
2
170
GitHub Copilot のテクニック集/GitHub Copilot Techniques
rayuron
36
13k
複雑性の高いオブジェクト編集に向き合う: プラガブルなReactフォーム設計
righttouch
PRO
0
110
Amazon VPC Lattice 最新アップデート紹介 - PrivateLink も似たようなアップデートあったけど違いとは
bigmuramura
0
190
KubeCon NA 2024 Recap / Running WebAssembly (Wasm) Workloads Side-by-Side with Container Workloads
z63d
1
250
どちらを使う?GitHub or Azure DevOps Ver. 24H2
kkamegawa
0
770
ゼロから創る横断SREチーム 挑戦と進化の軌跡
rvirus0817
2
270
生成AIのガバナンスの全体像と現実解
fnifni
1
190
Featured
See All Featured
Bash Introduction
62gerente
608
210k
A Modern Web Designer's Workflow
chriscoyier
693
190k
No one is an island. Learnings from fostering a developers community.
thoeni
19
3k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
44
6.9k
Put a Button on it: Removing Barriers to Going Fast.
kastner
59
3.6k
A Tale of Four Properties
chriscoyier
157
23k
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
2
290
KATA
mclloyd
29
14k
Statistics for Hackers
jakevdp
796
220k
The Illustrated Children's Guide to Kubernetes
chrisshort
48
48k
Build your cross-platform service in a week with App Engine
jlugia
229
18k
The Cost Of JavaScript in 2023
addyosmani
45
7k
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!