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

Ruby2.7のパターンマッチングで遊んでみた.pdf

 Ruby2.7のパターンマッチングで遊んでみた.pdf

RubyKaigiで発表されていた実例を元に実際にパターンマッチで遊んでみました。
https://speakerdeck.com/k_tsj/pattern-matching-new-feature-in-ruby-2-dot-7

Hiroki Kishi

October 24, 2019
Tweet

More Decks by Hiroki Kishi

Other Decks in Technology

Transcript

  1. Re:valua t ion https://fril.jp/ L ead & Delight User F

    irst Ownership Fail Smart 3VCZͷύλʔϯϚονϯάͰ༡ΜͰΈͨ
  2.   ύλʔϯϚονͷछྨ͸छྨ  ஋ͦͷ΋ͷʹϚονͤ͞Δ 7BMVFQBUUFSO   ม਺ʹΞαΠϯͤ͞Δ 7BSJBCMFQBUUFSO

      ͲΕ͔ʹϚονͤ͞Δʢ"MUFSOBUJWFQBUUFSOʣ  Ϛονͱม਺ʹΞαΠϯΛಉ࣌ʹߦ͏ "TQBUUFSO   "SSBZͷܗʹϚονͤ͞Δ "SSBZQBUUFSO   )BTIͷܗʹϚονͤ͞Δ )BTIQBUUFSO
  3.   ม਺ʹΞαΠϯͤ͞Δ 7BSJBCMFQBUUFSO ม਺ʹΞαΠϯͤ͞Δ͜ͱ͕Ͱ͖Δ 1 case 0 2 in

    a 3 p a #=> 0 4 end 1 case [0, 1] 2 in [_, _] 3 :reachable 4 end ม਺໊Λ@ʹ͢ΔͱɺϚον͸͢Δ͚Ͳ
 ΞαΠϯ͸͠ͳ͍ 1 a = 0 2 case 1 3 in ^a # means `in 0` 4 :unreachable 5 end #=> NoMatchingPatternError ͢Ͱʹଘࡏ͢Δม਺ͷ஋Λ࢖͍͍ͨ৔߹͸ɺ
 ?Λ࢖͏ &MJYJSͷQJOԋࢉࢠ
  4.   ͲΕ͔ʹϚονͤ͞Δʢ"MUFSOBUJWFQBUUFSOʣ c 03 Ͱෳ਺ఆٛͯ͠ɺ ͍ͣΕ͔͕ͰUSVFΛฦͤ͹ Ϛον͢Δ 1 ['a',

    1, :c].each do |value| 2 case value 3 in /a/ | 1 | Symbol 4 puts :reachable 5 end 6 end
  5.   Ϛονͱม਺ʹΞαΠϯΛಉ࣌ʹߦ͏ "TQBUUFSO Ϛονͨ͠ม਺Λ ଞͷม਺ʹΞαΠϯ͢Δ ʜ 1 ['a', 1,

    :c].each do |value| 2 case value 3 in /a/ | 1 | Symbol => bbb 4 puts bbb 5 end 6 end
  6.   "SSBZͷܗʹϚονͤ͞Δ "SSBZQBUUFSO ࡶʹݴ͏ͱʮܗʯΛ߹ΘͤΔͱɺϚον͢Δɻ TQMBU Ͱ࢒Γͷม਺ΛϚονͤͨ͞Γ΋Ͱ͖Δ 1 case [0,

    [1, 2]] 2 in [0, [1, _] => a] 3 p a #=> [1, 2] 4 end 2 in [0, [1, _] => a] ͔͠΋ɺͦͷͱ͖
 "TύλʔϯͰ஋ͷҰ෦ΛऔΓग़ͨ͠Γɺ Ϛονͨ͠஋ΛࣺͯͨΓͰ͖Δɻ
 ʢ͜͜·ͰͷύλʔϯͷԠ༻ʣ
  7.   "SSBZͷܗʹϚονͤ͞Δ "SSBZQBUUFSO 1 Color = Struct.new(:red, :green, :blue)

    do 2 def deconstruct 3 puts '`deconstruct` is called' 4 to_a # [red, green, blue] 5 end 6 end 7 8 class Color2 < Color; end 9 10 case Color[0, 10, 0] 11 in Color2[0, a, 0] # not called because type is different 12 puts "Color2" 13 in [0, a, 0] 14 puts "Matched with array: #{a}" # => 10 15 in Color[0, a, 0] # => `deconstruct` is called 16 puts "Matched with Color: #{a}" # => 10 17 end ಺෦తʹ͸ɺEFDPOTUSVDU͕ ฦ͢"SSBZΦϒδΣΫτΛݩ ʹύλʔϯϚον͍ͤͯ͞ Δɻ ͳͷͰɺಠࣗͷ$PMPSΫϥε ͷΦϒδΣΫτΛύλʔϯ Ϛονͤ͞Δ͜ͱ΋Մೳʂ ͍͢͝ʂ ຊՈεϥΠυͰ͸ɺߏจ໦Λॲཧ͢Δ3VCZ7."CTUSBDU4ZOUBY5SFF/PEFʹEFDPOTUSVDUΛ࣮૷ͨ͠Β 1PXFS"TTFSU͕࣮૷Ͱ͖ͪΌ͏తͳ͜ͱ͕ॻ͍ͯ͋Δʢཧղෆ଍ʣ
  8.   ̒)BTIͷܗʹϚονͤ͞Δ )BTIQBUUFSO 1 Person = Struct.new(:name, :age) do

    2 def deconstruct_keys(keys) 3 puts "`deconstruct_keys` is called with keys #{keys}" 4 { name: name } 5 end 6 end 7 8 case Person.new('a', 30) 9 in name: # => `deconstruct_keys` is called with keys [:name] 10 p name # => 'a' 11 end ಺෦తʹ͸ɺ EFDPOTUSVDU@LFZTͷLFZʹରԠ ͢ΔLFZWBMVFΛؚΉϋογϡ ͕ฦΕ͹Ϛονͤ͞Δ͜ͱ΋Ͱ ͖Δɻ ͳͷͰɺಠࣗͷ1FSTPOΫϥεͷ ΦϒδΣΫτΛύλʔϯϚον ͤ͞Δ͜ͱ΋Մೳʂ ͍͢͝ʂ \OBNFOBNF^ͷ4ZOUBY4VHBS
  9.   ࢖͍ॴ ύοͱࢥ͍͍ͭͨͷ͸ʜ w େྔσʔλΛ3VCZͰಡΈࠐΜͰɺύλʔϯʹϚονͨ͠ σʔλ͚ͩॲཧूܭ͢Δ w ಡΈࠐΈݩZBNM DTW

    KTPO BOZ/P42- w ͦ΋ͦ΋42-΍(SBQI2-ͳͲͰΫΤϦͰߜΓࠐΊΕ͹ۤ ࿑͸ͳ͍ w Ͳ͜Β΁ΜͰ࢖͑ΔͩΖ͏