Project

General

Profile

Actions

Feature #10327

open

Bool/False/True module for '==='

Added by arimay (yasuhiro arima) over 9 years ago. Updated over 9 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-dev:48593]

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

bool-false-true.patch (3.44 KB) bool-false-true.patch arimay (yasuhiro arima), 10/05/2014 04:01 PM
bool-falsy-truthy.patch (3.85 KB) bool-falsy-truthy.patch arimay (yasuhiro arima), 10/15/2014 02:31 PM
Actions

Also available in: Atom PDF

Like0
Like0Like0