1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby の case でワイルドカードのようなのが欲しい

Posted at

Scalaなら switch case で case("a", _)ってできるのだけど、
rubyだとできないので無理矢理やってみた。

_ = Object.new
def _.==(obj)
  true
end


[ ["a", 1], ["a", 2], ["b", 1], ["b", 2], ["c",  1], ["c", 3] ].each do |v|
  pattern = case v
    when ["a", 1 ] then "a,1"
    when ["a", _ ] then "a,*"
    when [_  , 1 ] then "*.1"
    when ["c", 1 ] then "c.1"  # not match
    when [_  , _ ] then "*.*"
    else "Not reach becase of [Any, Any] match all"
  end
  puts "#{v} => #{pattern}"
end

実行結果

["a", 1] => a,1
["a", 2] => a,*
["b", 1] => *.1
["b", 2] => *.*
["c", 1] => *.1
["c", 3] => *.*

_ って変数名普通に使っていいのだろうか?
anyとかの別の変数にしてもいいけど。

1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?