LoginSignup
9

More than 5 years have passed since last update.

ラムダおじさんの面白Proc#===講座

Last updated at Posted at 2012-10-03

Ruby1.9 から Proc#=== が追加され、 case 句の when の後ろにProcオブジェクトが使えるようになった。

以下のように利用できる。

def say_odd_or_even(num)
  case num
  when :even?.to_proc
    puts "#{num} is even"
  when :odd?.to_proc
    puts "#{num} is odd"
  else
    puts "WTF"
  end
end

で、 to_proc がかなりダサいので、こういうのはどうかと

module Kernel
  alias is lambda
end

def say_odd_or_even(num)
  case num
  when is(&:even?)
    puts "#{num} is even"
  when is(&:odd?)
    puts "#{num} is odd"
  else
    puts "WTF"
  end
end

思ったけど、やり過ぎ感高い。 〜完〜

追記

で、whenの後ろって確か「#===を実装しているオブジェクトなら何でもヨイ」はずだったので、

class Symbol
  def ===(obj)
    self.to_proc.call(obj)
  end
end

こうしたんですよ、そうしたらやっぱり、

(irb):4:in `call': undefined method `EXPR_BEG' for :EXPR_BEG:Symbol (NoMethodError)

って言われて irbごと(「Rubyごと」から修正)落ちました。同じようなことをする人がいたら危険なので共有します。!

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
What you can do with signing up
9