Actions
Feature #10327
openBool/False/True module for '==='
Feature #10327: Bool/False/True module for '==='
Status:
Open
Assignee:
-
Target version:
-
Description
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 を添えます。
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
Updated by znz (Kazuhiro NISHIYAMA) about 11 years ago
nil も含むなら False/True よりも Falsy/Truthy の方が良いのではないでしょうか。
case で使うだけなら :!.to_proc と :itself.to_proc を使うという方法もありそうです。
(itself は 2.2 以降ですが。)
ruby -e '[nil, false, true, 0].each do |obj| case obj when :!.to_proc; p [obj, false] when :itself.to_proc; p [obj, true] else p [obj, "-"] end end' [nil, false] [false, false] [true, true] [0, true]
Updated by arimay (yasuhiro arima) about 11 years ago
- File bool-falsy-truthy.patch bool-falsy-truthy.patch added
もっともなので Falsy/Truthy に変えてみました。
patch を作り直したので添付します。
前回の patch は壊れていました。確認が不十分でごめんなさい。
$ ./miniruby -e '[nil, false, true, 0].each {|obj| case obj when Falsy; p [obj, false] when Truthy; p [obj, true] else p [obj, "-"] end }' [nil, false] [false, false] [true, true] [0, true] また、to_proc を使う案ですが、短く書きたいのが主題なのでそれでは嬉しくないのです。
Actions