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
今更聞けない! Struct の使い方と今後の可能性について
Search
osyo
September 12, 2020
Programming
1.3k
3
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
今更聞けない! Struct の使い方と今後の可能性について
osyo
September 12, 2020
More Decks by osyo
See All by osyo
5分で話せる Ruby 3.1
osyo
0
210
AST を使って ActiveRecord の where の条件式をブロックで記述しよう
osyo
2
1.3k
Vim の開発環境自慢
osyo
5
3.1k
Use Macro all the time ~ マクロを使いまくろ ~ 感想戦
osyo
0
340
Use Macro all the time ~ マクロを使いまくろ ~ (English)
osyo
3
470
Use Macro all the time ~ マクロを使いまくろ ~ (日本語)
osyo
0
2.4k
月単位でイテレーションする
osyo
0
380
Ruby 3.0 で変わった private と attr_xxx
osyo
1
830
Ruby 2.0 から Ruby 3.0 を駆け足で振り返る
osyo
0
2.5k
Other Decks in Programming
See All in Programming
Hono + Inertia + React で LP を構築した話
oukayuka
2
180
tsc.rip を支える技術 / Kyoto.なんか #8
susisu
0
3.8k
Webエンジニアなのにブラウザの仕組みがわからないので、Pythonで自作してみた
tatsuki12
4
1.1k
DynamoDBの基礎を振り返りながらベクトル検索機能を理解する
musan
2
240
【QA Test Talk Vol.8】AI-DLC による Whole Team Approach の加速
pkshadeck
PRO
0
250
KotlinConf Extended South Korea 2026 Keynote
l2hyunwoo
0
120
Cloudflare is Agents
chimame
0
180
VibeCodingからAgenticWorkflowへ
starfish719
0
940
コンパウンドプロダクト開発のためのローカルプロセスマネージャー再発明 #layerxgo
izumin5210
0
450
Dockerfile CMD for Node.js
grazie1999
0
140
Flow は今どうなっているか
mizdra
PRO
0
760
PyConJP2026_wat_Python × Signal Processing: How to Draw Pictures with Sound Using Spectrogram Art
wat
0
570
Featured
See All Featured
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
659
62k
Stewardship and Sustainability of Urban and Community Forests
pwiseman
0
500
Believing is Seeing
oripsolob
1
200
Public Speaking Without Barfing On Your Shoes - THAT 2023
reverentgeek
1
550
Fireside Chat
paigeccino
42
4k
Google's AI Overviews - The New Search
badams
0
1.6k
Conquering PDFs: document understanding beyond plain text
inesmontani
PRO
4
3k
KATA
mclloyd
PRO
35
15k
My Coaching Mixtape
mlcsv
0
300
XXLCSS - How to scale CSS and keep your sanity
sugarenia
249
1.3M
Have SEOs Ruined the Internet? - User Awareness of SEO in 2025
akashhashmi
0
450
How Fast Is Fast Enough? [PerfNow 2025]
tammyeverts
3
830
Transcript
とちぎRuby 会議09 とちぎRuby 会議09 今更聞けない! 今更聞けない! Struct の使い⽅と今後の可能性 Struct の使い⽅と今後の可能性
について について
⾃⼰紹介 ⾃⼰紹介 名前:osyo Twitter : github : ブログ : Rails
歴2 年半 趣味で Ruby にパッチを投げたり bugs.ruby で気になったチケッ トをブログにまとめたりしてる Ruby で⼀番好きな機能は Refinements @pink_bangbi osyo-manga Secret Garden(Instrumental)
Struct の使い⽅と Struct の使い⽅と 今後の可能性について 今後の可能性について
Struct とは! Struct とは!
Struct とは Struct とは 任意のプロパティを持ったクラスを動的に⽣成する Ruby の標準 ライブラリ # 3
つのプロパティを持つ疑似クラスを作成する User = Struct.new(:id, :name, :age) # 作成した疑似クラスは通常のクラスと同じように使⽤できる # 引数は Struct.new に渡した順で割り当てられる homu = User.new(1, "homu", 14) # 各プロパティのアクセッサが暗黙的に定義されている p homu.name # => "homu" p homu.age # => 14 homu.age = 15 p homu.age # => 15
参照⽅法いろいろ 参照⽅法いろいろ # アクセッサメソッドとして参照できる p homu.name # => "homu" p
homu.age # => 14 # [] メソッドで参照 # Hash みたいにキーを渡してアクセス p homu[:name] # => "homu" # index を渡してアクセス p homu[1] # => 15 # Hash に変換できる p homu.to_h # => {:id=>1, :name=>"homu", :age=>14} # 未定義のプロパティにはアクセスできない p homu.hoge # error: undefined method `hoge' p homu[:foo] # error: `[]': no member 'foo' in struct (NameError)
定義⽅法いろいろ 定義⽅法いろいろ # 3 つのプロパティを持つ疑似クラスを作成する User = Struct.new(:id, :name, :age)
# User.new には Struct.new で渡した引数の順番で渡す User.new(1, "homu", 14) # Struct.new に keyword_init: true を渡すと User = Struct.new(:id, :name, :age, keyword_init: true) # User.new にキーワード引数で渡せるようになる p User.new(name: "homu", age: 14, id: 1) # => #<struct User id=1, name="homu", age=14> # Struct.new にブロックを渡し、その中でメソッドを定義すると # インスタンスメソッドとして定義される User = Struct.new(:last_name, :first_name) do def full_name "#{last_name} #{first_name}" end end homu = User.new(" 巴", " マミ") # ユーザが定義したインスタンスメソッドが呼べる p homu.full_name # => " 巴 マミ"
Struct ってどういう時に使うの? Struct ってどういう時に使うの?
Struct を継承する Struct を継承する Struct.new はクラスオブジェクトを返す なので Struct.new を継承することができる Struct.new
を継承することで Struct の便利メソッドがそのまま 使える!! class User < Struct.new(:last_name, :first_name, :age) def full_name "#{last_name} #{first_name}" end def to_s "#{full_name} #{age} 歳" end end homu = User.new(" 巴", " マミ", 15) # Struct のメソッドがそのまま使える p homu.last_name # => " 巴" p homu.to_h # => {:last_name=>" 巴", :first_name=>" マ ミ", :age=>15}
引数や戻り値の擬似オブジェクトとして使う 引数や戻り値の擬似オブジェクトとして使う その場でデータ構造を定義してオブジェクトを⽣成する事がで きる テストとかの mock オブジェクトとかでも利⽤できる 疑似ファイルをテスト上で定義したりとか API モジュールの戻り値として定義したりとか
def show_file(file) puts "path: #{file.path}" puts "size: #{file.size}" puts "lines:" puts file.readlines end # 普通はファイルを渡して使う show_file File.open("./test.rb") # Tempfile というクラスをその場で定義してそのインスタンスを渡す Tempfile = Struct.new(:path, :size, :readlines) show_file Tempfile.new("./test.rb", 14, %w(homu mami mado))
Struct の今後の可能性… ? Struct の今後の可能性… ?
Anonymous Struct literal という機能が提案されている ${} というリテラルで Struct のオブジェクトを定義できるよう にする提案 これを使うと
Hash みたいにカジュアルに Struct オブジェク トが使える [Feature #16986] Anonymous Struct literal [Feature #16986] Anonymous Struct literal # 今の書き⽅ Struct.new(:a, :b).new(1, 2) # 提案してるリテラルだと ${} で定義できる ${ a: 1, b: 2 } # さっきのコード例 Tempfile = Struct.new(:path, :size, :readlines) show_file Tempfile.new("./test.rb", 14, %w(homu mami mado)) # ${} ですっきりとかける show_file ${ path: "./test.rb", size: 14, readlines: %w(homu mami mado) }
Hash との⽐較例 Hash との⽐較例 # Hash homu = { id:
1, name: "homu", age: 14 } # [] でのみ要素にアクセスできる homu[:name] # 新しい要素を追加できる homu[:job] = " 魔法少⼥" # 存在しないキーにアクセスしてもエラーにならない homu[:nmae] # => nil # Anonymous Struct literal homu = ${ id: 1, name: "homu", age: 14 } # [] だけでなくて . で参照できる homu.name # 新しい要素は追加できない # そもそも存在しない要素にアクセスするとエラーになる homu[:job] = " 魔法少⼥" # error: undefined method `[]'
まだ議論中です! まだ議論中です!
今どうなってる? 今どうなってる? ⼊るかどうかすら決まってません!! いろんな書き⽅の提案がされている ${} の $ は Struct の
S です そういえば Rubykaigi で matz が新しいシンタックスを⼊れたく ないって⾔っていたような… ? https://bugs.ruby-lang.org/issues/16986#note-11 ${a:1, b:2} # 元々の提案 {|a:1, b:2|} # <- matz のアイデア struct a: 1, b: 2 # struct キーワードを追加 %o{a:1, b:2} # % 記法で定義 (a:1, b:2) # {} ではなくて () で定義 Struct.anonymous(a:1, b:2) # メソッド定義 Struct(a:1, b:2) Struct[a:1, b:2]
まとめ まとめ
まとめ まとめ Struct はその場でちょっとしたデータ構造を持つオブジェクト を定義する時に便利 継承して使うとそのクラスのプロパティ周りの処理がスッキリ する mock やダックタイピングで呼び出されるオブジェクトを定義す る時とかにも利⽤できる
Anonymous Struct literal ほしい!!! ${} みたいな機能は実装されてからみんな使い始めて便利、みた いになりそう
ご清聴 ご清聴 ありがとうございました ありがとうございました