From: arima.yasuhiro@... Date: 2014-10-05T16:09:18+00:00 Subject: [ruby-dev:48593] [ruby-trunk - Feature #10327] [Open] Bool/False/True module for '===' Issue #10327 has been reported by yasuhiro arima. ---------------------------------------- Feature #10327: Bool/False/True module for '===' https://bugs.ruby-lang.org/issues/10327 * Author: yasuhiro arima * Status: Open * Priority: Normal * Assignee: * Category: core * Target version: ---------------------------------------- ruby-core:0237 から始まる Boolean Class の話題で Boolean Module が提案されていました。 それは必要とされているのか?という疑問とともに .true? メソッドなどが議論されていました。 それを読んで、=== メソッドを利用する Bool, False, True Module を書いてみました。 これを使うと case 式で when TrueClass, FalseClass ではなく when Bool と短く書けます。 また、case 式で 偽は when nil, false ではなく when False と書けます。 そして、真は else ではなく when True と書けます。 Bool, False, True という名前にしたのは、短く書きたいことと、リファレンスマニュアルでも使われているためです。 以下の ruby コードとほぼ同じ内容を C で書いた patch を添えます。 ~~~ruby module Bool def self.append_features(m) if ((m != FalseClass) and (m != TrueClass)) raise TypeError, "`#{m.name}' isn't FalseClass nor TrueClass", caller(1) end super end end class FalseClass include Bool end class TrueClass include Bool end module False def self.===(other) other.nil? || other == false end end module True def self.===(other) !other.nil? && other != false end end ~~~ 以下が実行例です。 ~~~ $ ./miniruby -e 'class String; include Bool; end;' -e:1:in `append_features': 'String' isn't FalseClass nor TrueClass (TypeError) from -e:1:in `include' from -e:1:in `<class:String>' from -e:1:in `<main>' $ ./miniruby -e '[nil, false, true, 0].each {|obj| p obj.class.ancestors}' [NilClass, Object, Kernel, BasicObject] [FalseClass, Bool, Object, Kernel, BasicObject] [TrueClass, Bool, Object, Kernel, BasicObject] [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject] $ ./miniruby -e '[nil, false, true, 0].each {|obj| case obj when Bool; p [obj, Bool] else p [obj, "-"] end }' [nil, "-"] [false, Bool] [true, Bool] [0, "-"] $ ./miniruby -e '[nil, false, true, 0].each {|obj| case obj when False; p [obj, false] when True; p [obj, true] else p [obj, "-"] end }' [nil, false] [false, false] [true, true] [0, true] ~~~ ---Files-------------------------------- bool-false-true.patch (3.44 KB) -- https://bugs.ruby-lang.org/