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
Coercion in Ruby
Search
Grzegorz Witek
May 09, 2018
Technology
1
96
Coercion in Ruby
Grzegorz Witek
May 09, 2018
Tweet
Share
More Decks by Grzegorz Witek
See All by Grzegorz Witek
One Year with Hanami
arnvald
0
59
Writing config files in Ruby
arnvald
0
87
Speaking at RDRC
arnvald
0
81
Read more
arnvald
2
64
Your API is too slow!
arnvald
0
650
The simplest gem you'll ever use
arnvald
0
61
International to global
arnvald
0
55
Patterns, patterns everywhere
arnvald
0
63
Nomadic programmer - Baruco 2014 edition
arnvald
0
120
Other Decks in Technology
See All in Technology
Cursor AgentによるパーソナルAIアシスタント育成入門―業務のプロンプト化・MCPの活用
os1ma
9
3.1k
LangfuseでAIエージェントの 可観測性を高めよう!/Enhancing AI Agent Observability with Langfuse!
jnymyk
0
170
Vision Pro X Text to 3D Model ~How Swift and Generative Al Unlock a New Era of Spatial Computing~
igaryo0506
0
260
改めて学ぶ Trait の使い方 / phpcon odawara 2025
meihei3
1
570
LLM as プロダクト開発のパワードスーツ
layerx
PRO
1
200
JPOUG Tech Talk #12 UNDO Tablespace Reintroduction
nori_shinoda
1
120
От ручной разметки к LLM: как мы создавали облако тегов в Lamoda. Анастасия Ангелова, Data Scientist, Lamoda Tech
lamodatech
0
330
Стильный код: натуральный поиск редких атрибутов по картинке. Юлия Антохина, Data Scientist, Lamoda Tech
lamodatech
0
330
20250413_湘南kaggler会_音声認識で使うのってメルス・・・なんだっけ?
sugupoko
1
390
Webアプリを Lambdaで動かすまでに考えること / How to implement monolithic Lambda Web Application
_kensh
7
1.2k
DuckDB MCPサーバーを使ってAWSコストを分析させてみた / AWS cost analysis with DuckDB MCP server
masahirokawahara
0
700
AWSLambdaMCPServerを使ってツールとMCPサーバを分離する
tkikuchi
1
2.5k
Featured
See All Featured
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Done Done
chrislema
183
16k
Code Review Best Practice
trishagee
67
18k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
13
1.4k
The Power of CSS Pseudo Elements
geoffreycrofte
75
5.7k
Building a Scalable Design System with Sketch
lauravandoore
462
33k
Principles of Awesome APIs and How to Build Them.
keavy
126
17k
Optimising Largest Contentful Paint
csswizardry
36
3.2k
Why Our Code Smells
bkeepers
PRO
336
57k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
23
2.6k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
356
30k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
60k
Transcript
Coercion in Ruby Between the strong and weak typing
Grzegorz Witek
Strong vs. weak typing $> 3 + “a” Python: unsupported
operand type(s) for +: 'int' and 'str' Ruby: String can't be coerced into Fixnum Javascript: “3a”
Strong vs. weak typing $> 3 + “a” Python: unsupported
operand type(s) for +: 'int' and 'str' Ruby: String can't be coerced into Fixnum Javascript: “3a”
Coercion in Ruby class Money < Struct.new(:amount) def *(value) amount
* value end end
How do I Ruby? money = Money.new(3) money * 2
# => 6 2 * money # => ERROR U FAIL
Bad solution class Fixnum alias :old_multiply :* def *(val) if
defined?(Money) && val.is_a?(Money) return self * val.amount else old_multiply(val) end end end
Bad solution Pros: works Cons: it’s wrong on as many
levels as you can imagine
Good solution class Money < Struct.new(:amount) def *(value) amount
* value end def coerce(other) [self, other] end end
Good solution def coerce(other) [self, other] end
Good solution def coerce(other) [other, amount] end
How does it work? Short answer: when Ruby can’t handle
the param type, it calls arg.coerce(self) it gets 2 elements array, and calls array[0].method(array[1])
How does it work? Fixnum#*(Money) => omg, what to do?
How does it work? Fixnum#(Money)* => omg, what to do?
Money#coerce => [Money, Fixnum]
How does it work? Fixnum#*(Money) => omg, what to do?
Money#coerce => [Money, Fixnum] Money#*(Fixnum) => I know how to handle it!
Coercion in Ruby Thanks! Grzegorz Witek @arnvald