Upgrade to Pro — share decks privately, control downloads, hide ads and more …

お前はまだRubyの 型の強さを知らない

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.

お前はまだRubyの 型の強さを知らない

Avatar for すぎうり

すぎうり

June 23, 2026

More Decks by すぎうり

Other Decks in Programming

Transcript

  1. 自己紹介 すぎうり • Twitter:@uproad3 • Ruby歴20年 • VRChat歴7年 • 仕事:Rails |

    AWS | LT芸人 • 趣味:アーキテクト | リファクタリング | 電子工作 • 言語:Ruby | C# | C | JS | ほかいろいろ • 技術:Terraform | Unity | Ubuntu | MySQL | RaspberryPi • 悲しきフルスタックエンジニア • 最近はClaudeをシバきまわしている • 特に型に強い思い入れがあるわけではない
  2. 暗黙的型変換をする言語 JavaScript 1 + "2" // => "12" ← 数値が文字列に化ける

    C言語 int i = 1; float f = 2.5; float result = i + f; // int が暗黙的に float に昇格 → 便利だが、意図しない変換が潜む
  3. Rubyは変換しない 3 + '1' # => TypeError: String can't be

    coerced into Integer Rubyは黙って変換しない。おかしければ怒る。 これが「型の強さ」 変換したいなら明示的に: 3 + '1'.to_i # => 4 3.to_s + '1' # => '31'
  4. String#+ は相手の to_str を呼ぶ コード例 # to_str なし → TypeError

    class MyStr def initialize(s); @s = s; end end "Hello " + MyStr.new("world") # => TypeError # to_str あり → 成功 class MyStr def to_str; @s; end end "Hello " + MyStr.new("world") # => "Hello world" String#+ の擬似コード def +(other) if other.respond_to?(:to_str) # to_str を呼んで文字列化 concat(other.to_str) else raise TypeError, "no implicit conversion" end end ※ 実際はC実装。Ruby擬似コードに変換
  5. Numeric#+ は相手の coerce を呼ぶ コード例 class Money def initialize(v); @v

    = v; end def coerce(other) [Money.new(other), self] end def +(other) Money.new(@v + other.to_i) end end 2 + Money.new(100) # => Money(102) Numeric#+ の擬似コード def +(other) # 同じ型なら直接計算 return numeric_add(other) if other.is_a?(Numeric) # 異なる型は coerce を期待 x, y = other.coerce(self) x + y rescue TypeError raise TypeError, "can't coerce" end ※ 実際はC実装。Ruby擬似コードに変換
  6. Rubyは相手が変換方法を知っていることを期待する String#+ to_str を持ってる? 持っていれば文字列 として扱う 持っていなければ TypeError Numeric#+ coerce

    を持ってる? 持っていれば演算可 能として扱う 持っていなければ TypeError 共通の思想 暗黙的に変換しない 変換方法を知って いるかを確かめて から使う 型は強い。でも、変換方法を提供できる ——これがRubyの「開かれた強さ」