Ruby:如何将字符串转换为布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36228873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby: How to convert a string to boolean
提问by emery
I have a value that will be one of four things: boolean true, boolean false, the string "true", or the string "false". I want to convert the string to a boolean if it is a string, otherwise leave it unmodified. In other words:
我有一个值,它将是四件事之一:布尔真、布尔假、字符串“真”或字符串“假”。如果字符串是字符串,我想将字符串转换为布尔值,否则保持不变。换句话说:
"true" should become true
“真”应该变成真
"false" should become false
“假”应该变成假
true should stay true
真实应该保持真实
false should stay false
假应该保持假
回答by steenslag
def true?(obj)
obj.to_s.downcase == "true"
end
回答by rado
If you use Rails 5, you can do ActiveModel::Type::Boolean.new.cast(value).
如果您使用 Rails 5,则可以执行ActiveModel::Type::Boolean.new.cast(value).
In Rails 4.2, use ActiveRecord::Type::Boolean.new.type_cast_from_user(value).
在 Rails 4.2 中,使用 ActiveRecord::Type::Boolean.new.type_cast_from_user(value).
The behavior is slightly different, as in Rails 4.2, the true value and false values are checked. In Rails 5, only false values are checked - unless the values is nil or matches a false value, it is assumed to be true. False values are the same in both versions:
FALSE_VALUES = [false, 0, "0", "f", "F", "false", "FALSE", "off", "OFF"]
行为略有不同,如在 Rails 4.2 中,检查真值和假值。在 Rails 5 中,只检查假值 - 除非值为零或匹配假值,否则假定为真。两个版本中的假值相同:
FALSE_VALUES = [false, 0, "0", "f", "F", "false", "FALSE", "off", "OFF"]
Rails 5 Source: https://github.com/rails/rails/blob/5-1-stable/activemodel/lib/active_model/type/boolean.rb
Rails 5 来源:https: //github.com/rails/rails/blob/5-1-stable/activemodel/lib/active_model/type/boolean.rb
回答by Steve Craig
I've frequently used this pattern to extend the core behavior of Ruby to make it easier to deal with converting arbitrary data types to boolean values, which makes it really easy to deal with varying URL parameters, etc.
我经常使用这种模式来扩展 Ruby 的核心行为,以便更容易地处理将任意数据类型转换为布尔值,这使得处理不同的 URL 参数等变得非常容易。
class String
def to_boolean
ActiveRecord::Type::Boolean.new.cast(self)
end
end
class NilClass
def to_boolean
false
end
end
class TrueClass
def to_boolean
true
end
def to_i
1
end
end
class FalseClass
def to_boolean
false
end
def to_i
0
end
end
class Integer
def to_boolean
to_s.to_boolean
end
end
So let's say you have a parameter foowhich can be:
因此,假设您有一个参数foo,它可以是:
- an integer (0 is false, all others are true)
- a true boolean (true/false)
- a string ("true", "false", "0", "1", "TRUE", "FALSE")
- nil
- 一个整数(0 为假,所有其他为真)
- 一个真正的布尔值(真/假)
- 一个字符串(“真”、“假”、“0”、“1”、“真”、“假”)
- 零
Instead of using a bunch of conditionals, you can just call foo.to_booleanand it will do the rest of the magic for you.
而不是使用一堆条件,你可以直接调用foo.to_boolean,它会为你完成剩下的魔法。
In Rails, I add this to an initializer named core_ext.rbin nearly all of my projects since this pattern is so common.
在 Rails 中,我将它添加到core_ext.rb我几乎所有项目中命名的初始化程序中,因为这种模式非常普遍。
## EXAMPLES
nil.to_boolean == false
true.to_boolean == true
false.to_boolean == false
0.to_boolean == false
1.to_boolean == true
99.to_boolean == true
"true".to_boolean == true
"foo".to_boolean == true
"false".to_boolean == false
"TRUE".to_boolean == true
"FALSE".to_boolean == false
"0".to_boolean == false
"1".to_boolean == true
true.to_i == 1
false.to_i == 0
回答by David Foley
Don't think too much:
不要想太多:
bool_or_string.to_s == "true"
So,
所以,
"true".to_s == "true" #true
"false".to_s == "true" #false
true.to_s == "true" #true
false.to_s == "true" #false
You could also add ".downcase," if you are worried about capital letters.
如果您担心大写字母,您还可以添加“.downcase”。
回答by archana
if value.to_s == 'true'
true
elsif value.to_s == 'false'
false
end
回答by Cary Swoveland
h = { "true"=>true, true=>true, "false"=>false, false=>false }
["true", true, "false", false].map { |e| h[e] }
#=> [true, true, false, false]
回答by mnishiguchi
In a rails 5.1 app, I use this core extension built on top of ActiveRecord::Type::Boolean. It is working perfectly for me when I deserialize boolean from JSON string.
在 rails 5.1 应用程序中,我使用构建在ActiveRecord::Type::Boolean. 当我从 JSON 字符串反序列化布尔值时,它对我来说非常有效。
https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html
https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html
# app/lib/core_extensions/string.rb
module CoreExtensions
module String
def to_bool
ActiveRecord::Type::Boolean.new.deserialize(downcase.strip)
end
end
end
initialize core extensions
初始化核心扩展
# config/initializers/core_extensions.rb
String.include CoreExtensions::String
rspec
规格
# spec/lib/core_extensions/string_spec.rb
describe CoreExtensions::String do
describe "#to_bool" do
%w[0 f F false FALSE False off OFF Off].each do |falsey_string|
it "converts #{falsey_string} to false" do
expect(falsey_string.to_bool).to eq(false)
end
end
end
end
回答by equivalent8
In Rails I prefer using ActiveModel::Type::Boolean.new.cast(value)as mentioned in other answers here
在 Rails 中,我更喜欢使用ActiveModel::Type::Boolean.new.cast(value)这里的其他答案中提到的
But when I write plain Ruby lib. then I use a hack where JSON.parse(standard Ruby library) will convert string "true" to trueand "false" to false. E.g.:
但是当我编写普通的 Ruby 库时。然后我使用一个 hack,其中 JSON.parse(标准 Ruby 库)将字符串“true”转换为true“false”到false. 例如:
require 'json'
azure_cli_response = `az group exists --name derrentest` # => "true\n"
JSON.parse(azure_cli_response) # => true
azure_cli_response = `az group exists --name derrentesttt` # => "false\n"
JSON.parse(azure_cli_response) # => false
Example from live application:
来自实时应用程序的示例:
require 'json'
if JSON.parse(`az group exists --name derrentest`)
`az group create --name derrentest --location uksouth`
end
confirmed under Ruby 2.5.1
在 Ruby 2.5.1 下确认
回答by Felipe Funes
I have a little hack for this one. JSON.parse('false')will return falseand JSON.parse('true')will return true. But this doesn't work with JSON.parse(true || false). So, if you use something like JSON.parse(your_value.to_s)it should achieve your goal in a simple but hacky way.
我有一个小技巧。JSON.parse('false')将返回false和JSON.parse('true')将返回true。但这不适用于JSON.parse(true || false). 所以,如果你使用类似的东西JSON.parse(your_value.to_s)应该以一种简单但很hacky的方式实现你的目标。
回答by emery
A gem like https://rubygems.org/gems/to_boolcan be used, but it can easily be written in one line using a regex or ternary.
可以使用像https://rubygems.org/gems/to_bool这样的 gem ,但可以使用正则表达式或三元轻松将其写成一行。
regex example:
正则表达式示例:
boolean = (var.to_s =~ /^true$/i) == 0
ternary example:
三元示例:
boolean = var.to_s.eql?('true') ? true : false
The advantage to the regex method is that regular expressions are flexible and can match a wide variety of patterns. For example, if you suspect that var could be any of "True", "False", 'T', 'F', 't', or 'f', then you can modify the regex:
regex 方法的优点是正则表达式很灵活,可以匹配多种模式。例如,如果您怀疑 var 可能是“True”、“False”、“T”、“F”、“t”或“f”中的任何一个,那么您可以修改正则表达式:
boolean = (var.to_s =~ /^[Tt].*$/i) == 0

