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
MLOps の現場から
asei
7
650
株式会社ログラス − エンジニア向け会社説明資料 / Loglass Comapany Deck for Engineer
loglass2019
3
32k
KubeCon NA 2024 Recap: How to Move from Ingress to Gateway API with Minimal Hassle
ysakotch
0
210
多領域インシデントマネジメントへの挑戦:ハードウェアとソフトウェアの融合が生む課題/Challenge to multidisciplinary incident management: Issues created by the fusion of hardware and software
bitkey
PRO
2
110
サービスでLLMを採用したばっかりに振り回され続けたこの一年のあれやこれや
segavvy
2
490
フロントエンド設計にモブ設計を導入してみた / 20241212_cloudsign_TechFrontMeetup
bengo4com
0
1.9k
大幅アップデートされたRagas v0.2をキャッチアップ
os1ma
2
540
Storage Browser for Amazon S3
miu_crescent
1
230
生成AIのガバナンスの全体像と現実解
fnifni
1
190
NilAway による静的解析で「10 億ドル」を節約する #kyotogo / Kyoto Go 56th
ytaka23
3
380
サーバレスアプリ開発者向けアップデートをキャッチアップしてきた #AWSreInvent #regrowth_fuk
drumnistnakano
0
200
統計データで2024年の クラウド・インフラ動向を眺める
ysknsid25
2
850
Featured
See All Featured
Designing Experiences People Love
moore
138
23k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
44
6.9k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
Into the Great Unknown - MozCon
thekraken
33
1.5k
Thoughts on Productivity
jonyablonski
67
4.4k
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
2
170
[RailsConf 2023] Rails as a piece of cake
palkan
53
5k
RailsConf 2023
tenderlove
29
940
Build your cross-platform service in a week with App Engine
jlugia
229
18k
Building a Modern Day E-commerce SEO Strategy
aleyda
38
7k
Bootstrapping a Software Product
garrettdimon
PRO
305
110k
The World Runs on Bad Software
bkeepers
PRO
65
11k
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!