9
7

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.

Symbol#to_procに引数を指定できるようにしてみる

Last updated at Posted at 2014-02-16

アイデアとしては以前からあるけど、とにかく簡潔に書きたかったので、以下のようにしてみた。

class Symbol
  def to_proc(*args)
    -> receiver { receiver.send(self, *args) }
  end
  alias_method :[], :to_proc
end

Symbol#[] はもともとあって String#[] と同じだけど、普通使わないし上書きして良いよね?

puts (0..5).map(&:*[10])

だから何という感じだけど、応用でwhenで比較演算子がかける。

[1, 10, 100].each do |number|

  puts "#{number} is"

  case number
  when :<[5]   then puts "less than 5."
  when :<[50]  then puts "less than 50."
  when :<[500] then puts "less than 500."
  end

  case number
  when :>[50] then puts "more than 50."
  when :>[5]  then puts "more than 5."
  when :>[0]  then puts "more than 0."
  end

end

そもそも何がしたかったかというと、これがやりたかった。

module Kernel
  def less(boundary)
    :<[boundary]
  end

  def more(boundary)
    :>[boundary]
  end
end

[1, 10, 100].each do |number|

  puts "#{number} is"

  case number
  when less(5)   then puts "less than 5."
  when less(50)  then puts "less than 50."
  when less(500) then puts "less than 500."
  end

  case number
  when more(50) then puts "more than 50."
  when more(5)  then puts "more than 5."
  when more(0)  then puts "more than 0."
  end

end

ところで

Repro株式会社 では一緒に切磋琢磨できる仲間を募集しています! ぜひこちらをごらんください!

9
7
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
9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?