case"aabbcabcdd".split(//,0) in [ *pre, "a"=>x, "b"=>y, *post ] p pre p x p y p post end #["a"] #"a" #"b" #["b", "c", "a", "b", "c", "d", "d"]
# caseの結果を変数に返すことができる result = case"aabbcabc".split(//,0) in [ *pre, "a"=>x, "b"=>y, *post ] post.join() end
p result # =>bcabcdd
# マッチしないと警告(NoMatchingPatternError)を出すので、対応しておくのがよさそう # "1" | "2" | "3" => y みたいに使用して or の表現もできる result = begin case"aabbcaa31bcdd".split(//,0) in [ *pre, "a" => x, "1" | "2" | "3" => y, *post ] { pre: pre, x: x, y: y, post: post } end rescue nil end
p result #=> {:pre=>["a", "a", "b", "b", "c", "a"], :x=>"a", :y=>"3", :post=>["1", "b", "c", "d", "d"]}
# 文字列や数字でなくてもOK # 前後を使用しない場合は*だけでOK result = begin case {type:"fish", orders:[ { name:"maguro", count:3}, { name:"hamachi", count:4}, { name:"iwashi", count:5}] } in {type:"fish", orders:[ *, {name:"hamachi", count: count }, *]} count end rescue nil end
p result # =>4
並列実行 Ractor の導入
外部のライブラリ無く単独で並列実行機能があるのすごいよね。
動作確認
test5.rb
1 2 3 4 5 6 7 8 9
5.times.each do |t| Ractor.new t do |n| puts "count#{n}" end end