Skip to content

Instantly share code, notes, and snippets.

@pasela
Created August 21, 2015 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pasela/9226680724421fd9d720 to your computer and use it in GitHub Desktop.
Save pasela/9226680724421fd9d720 to your computer and use it in GitHub Desktop.
[ruby] parse_bool.rb
# encoding: utf-8
# 論理値に変換する
#
# falseとなる値
# nil, false, 0
# falseとなる文字列(大文字小文字区別なし)
# 0, 0.0, f, false, n, no, off, 空文字, 空白文字のみ
# trueとなるもの
# 上記以外
#
# @param [Object] value 評価する値
# @return [Boolean]
def parse_bool(value)
case value
when nil, false, 0
return false
end
str = value.to_s.strip
return false if str.empty? || /\A(?:0+|0*\.0+|f|false|n|no|off)\z/i =~ str
true
end
# encoding: utf-8
require "minitest/autorun"
require_relative "parse_bool"
# test for parse_bool method.
class TestParseBool < MiniTest::Test
params = {
'nil' => [false, nil],
'false' => [false, false],
'0' => [false, 0],
'""' => [false, ""],
'" "' => [false, " "],
'" \t "' => [false, " \t "],
'"false"' => [false, "false"],
'"FALSE"' => [false, "FALSE"],
'"FaLsE"' => [false, "FaLsE"],
'"f"' => [false, "f"],
'"n"' => [false, "n"],
'"no"' => [false, "no"],
'"off"' => [false, "off"],
'"0"' => [false, "0"],
'"000"' => [false, "000"],
'"0.0"' => [false, "0.0"],
'"000.000"' => [false, "000.000"],
'".0"' => [false, ".0"],
'true' => [true, true],
'1' => [true, 1],
'999' => [true, 999],
'"true"' => [true, "true"],
'"TRUE"' => [true, "TRUE"],
'"TrUe"' => [true, "TrUe"],
'"t"' => [true, "t"],
'"yes"' => [true, "yes"],
'"y"' => [true, "y"],
'"on"' => [true, "on"],
'"1"' => [true, "1"],
'"0.1"' => [true, "0.1"],
'"a"' => [true, "a"],
'"+"' => [true, "+"],
'"nil"' => [true, "nil"],
'object' => [true, Object.new],
}
params.each do |name, (expected, target)|
define_method("test_#{name}") do
assert_equal(expected, parse_bool(target))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment