Ruby:如何将字符串转换成布尔值

时间:2021-09-25 21:44:58

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:

我有一个值,它是4个值中的一个:boolean true、boolean false、字符串“true”或字符串“false”。如果字符串是字符串,我想把它转换成布尔值,否则不修改它。换句话说:

"true" should become true

“true”应该成为真的

"false" should become false

“false”应该成为错误的

true should stay true

真应该保持真

false should stay false

假应保持假

10 个解决方案

#1


68  

def true?(obj)
  obj.to_s == "true"
end

#2


41  

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(值)。

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中所示,将检查true值和false值。在Rails 5中,只检查假值—除非值为nil或匹配假值,否则假定它为真。错误值在两个版本中都是相同的:False值= [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

#3


12  

if value.to_s == 'true'
  true
elsif value.to_s == 'false'
  false
end

#4


12  

h = { "true"=>true, true=>true, "false"=>false, false=>false }

["true", true, "false", false].map { |e| h[e] }
  #=> [true, true, false, false] 

#5


10  

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 foo which can be:

假设有一个参数foo可以是:

  • an integer (0 is false, all others are true)
  • 整数(0为假,其它都为真)
  • a true boolean (true/false)
  • 一个真正的布尔(真/假)
  • a string ("true", "false", "0", "1", "TRUE", "FALSE")
  • 一个字符串(“真正的”,“假”,“0”,“1”,“真正的”,“假”)
  • nil

Instead of using a bunch of conditionals, you can just call foo.to_boolean and it will do the rest of the magic for you.

不用很多条件语句,你可以直接调用foo。to_boolean就能帮你完成剩下的魔术。

In Rails, I add this to an initializer named core_ext.rb in 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

#6


10  

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,“如果你担心大写字母。

#7


3  

Although I like the hash approach (I've used it in the past for similar stuff), given that you only really care about matching truthy values - since - everything else is false - you can check for inclusion in an array:

尽管我喜欢散列方法(我以前也用过类似的方法),但考虑到您只关心匹配真实值——因为——其他都是假的——您可以检查数组中的包含情况:

value = [true, 'true'].include?(value)

or if other values could be deemed truthy:

或者如果其他的价值可以被认为是真实的:

value = [1, true, '1', 'true'].include?(value)

you'd have to do other stuff if your original value might be mixed case:

如果你的原始价值可能是混合情况,你必须做其他的事情:

value = value.to_s.downcase == 'true'

but again, for your specific description of your problem, you could get away with that last example as your solution.

但是,对于你的问题的具体描述,你可以用最后一个例子作为你的解决方案。

#8


2  

A gem like https://rubygems.org/gems/to_bool can be used, but it can easily be written in one line using a regex or ternary.

可以使用https://rubygems.org/gems/to_bool之类的gem,但是可以使用regex或ternary轻松地在一行中编写。

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”,那么您可以修改regex:

boolean = (var.to_s =~ /^[Tt].*$/i) == 0

#9


1  

In rails, I've previously done something like this:

在rails中,我以前做过这样的事情:

class ApplicationController < ActionController::Base
  # ...

  private def bool_from(value)
    !!ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
  end
  helper_method :bool_from

  # ...
end

Which is nice if you're trying to match your boolean strings comparisons in the same manner as rails would for your database.

如果您试图以与数据库的rails相同的方式匹配布尔字符串比较,这是很好的。

#10


-4  

What about smthing like:

smthing呢:

boolean_str = 'false'
boolean = eval(boolean_str)

#1


68  

def true?(obj)
  obj.to_s == "true"
end

#2


41  

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(值)。

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中所示,将检查true值和false值。在Rails 5中,只检查假值—除非值为nil或匹配假值,否则假定它为真。错误值在两个版本中都是相同的:False值= [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

#3


12  

if value.to_s == 'true'
  true
elsif value.to_s == 'false'
  false
end

#4


12  

h = { "true"=>true, true=>true, "false"=>false, false=>false }

["true", true, "false", false].map { |e| h[e] }
  #=> [true, true, false, false] 

#5


10  

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 foo which can be:

假设有一个参数foo可以是:

  • an integer (0 is false, all others are true)
  • 整数(0为假,其它都为真)
  • a true boolean (true/false)
  • 一个真正的布尔(真/假)
  • a string ("true", "false", "0", "1", "TRUE", "FALSE")
  • 一个字符串(“真正的”,“假”,“0”,“1”,“真正的”,“假”)
  • nil

Instead of using a bunch of conditionals, you can just call foo.to_boolean and it will do the rest of the magic for you.

不用很多条件语句,你可以直接调用foo。to_boolean就能帮你完成剩下的魔术。

In Rails, I add this to an initializer named core_ext.rb in 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

#6


10  

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,“如果你担心大写字母。

#7


3  

Although I like the hash approach (I've used it in the past for similar stuff), given that you only really care about matching truthy values - since - everything else is false - you can check for inclusion in an array:

尽管我喜欢散列方法(我以前也用过类似的方法),但考虑到您只关心匹配真实值——因为——其他都是假的——您可以检查数组中的包含情况:

value = [true, 'true'].include?(value)

or if other values could be deemed truthy:

或者如果其他的价值可以被认为是真实的:

value = [1, true, '1', 'true'].include?(value)

you'd have to do other stuff if your original value might be mixed case:

如果你的原始价值可能是混合情况,你必须做其他的事情:

value = value.to_s.downcase == 'true'

but again, for your specific description of your problem, you could get away with that last example as your solution.

但是,对于你的问题的具体描述,你可以用最后一个例子作为你的解决方案。

#8


2  

A gem like https://rubygems.org/gems/to_bool can be used, but it can easily be written in one line using a regex or ternary.

可以使用https://rubygems.org/gems/to_bool之类的gem,但是可以使用regex或ternary轻松地在一行中编写。

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”,那么您可以修改regex:

boolean = (var.to_s =~ /^[Tt].*$/i) == 0

#9


1  

In rails, I've previously done something like this:

在rails中,我以前做过这样的事情:

class ApplicationController < ActionController::Base
  # ...

  private def bool_from(value)
    !!ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
  end
  helper_method :bool_from

  # ...
end

Which is nice if you're trying to match your boolean strings comparisons in the same manner as rails would for your database.

如果您试图以与数据库的rails相同的方式匹配布尔字符串比较,这是很好的。

#10


-4  

What about smthing like:

smthing呢:

boolean_str = 'false'
boolean = eval(boolean_str)