jQuery 字符串“真”和“假”到布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8119970/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:03:06  来源:igfitidea点击:

String "true" and "false" to boolean

jqueryruby-on-railsrubyruby-on-rails-3

提问by davidb

I have a Rails application and I'm using jQuery to query my search view in the background. There are fields q(search term), start_date, end_dateand internal. The internalfield is a checkbox and I'm using the is(:checked)method to build the url that is queried:

我有一个 Rails 应用程序,我正在使用 jQuery 在后台查询我的搜索视图。有字段q(搜索词)start_dateend_dateinternal。该internal字段是一个复选框,我正在使用该is(:checked)方法来构建被查询的 url:

$.getScript(document.URL + "?q=" + $("#search_q").val() + "&start_date=" + $("#search_start_date").val() + "&end_date=" + $("#search_end_date").val() + "&internal=" + $("#search_internal").is(':checked'));

Now my problem is in params[:internal]because there is a string either containing "true" or "false" and I need to cast it to boolean. Of course I can do it like this:

现在我的问题是params[:internal]因为有一个包含“true”或“false”的字符串,我需要将它转换为布尔值。当然我可以这样做:

def to_boolean(str)
     return true if str=="true"
     return false if str=="false"
     return nil
end

But I think there must be a more Ruby'ish way to deal with this problem! Isn't there...?

但我认为必须有一种更像 Ruby 风格的方式来处理这个问题!不是有……吗?

回答by cvshepherd

As far as i know there is no built in way of casting strings to booleans, but if your strings only consist of 'true'and 'false'you could shorten your method to the following:

据我所知,没有内置的将字符串转换为布尔值的方法,但是如果您的字符串只包含'true'并且'false'您可以将您的方法缩短为以下内容:

def to_boolean(str)
  str == 'true'
end

回答by Satya Kalluri

ActiveRecord provides a clean way of doing this.

ActiveRecord 提供了一种干净的方法来做到这一点。

def is_true?(string)
  ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(string)
end

ActiveRecord::ConnectionAdapters::Column::TRUE_VALUEShas all of the obvious representations of True values as strings.

ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES将 True 值的所有明显表示都作为字符串。

回答by Halil ?zgür

Security Notice

安全须知

Note that this answer in its bare form is only appropriate for the other use case listed below rather than the one in the question. While mostly fixed, there have been numerous YAML related security vulnerabilitieswhich were caused by loading user input as YAML.

请注意,这个简单形式的答案仅适用于下面列出的其他用例,而不是问题中的用例。虽然大部分已修复,但仍有许多与 YAML 相关的安全漏洞是由将用户输入加载为 YAML 引起的。



A trick I use for converting strings to bools is YAML.load, e.g.:

我用于将字符串转换为 bool 的一个技巧是YAML.load,例如:

YAML.load(var) # -> true/false if it's one of the below

YAML boolaccepts quite a lot of truthy/falsy strings:

YAML bool接受相当多的真/假字符串:

y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF

Another use case

另一个用例

Assume that you have a piece of config code like this:

假设你有一段这样的配置代码:

config.etc.something = ENV['ETC_SOMETHING']

And in command line:

并在命令行中:

$ export ETC_SOMETHING=false

Now since ENVvars are strings once inside code, config.etc.something's value would be the string "false"and it would incorrectly evaluate to true. But if you do like this:

现在,由于ENVvars 是代码config.etc.something中的字符串"false",因此的值将是字符串,并且会错误地计算为true. 但如果你这样做:

config.etc.something = YAML.load(ENV['ETC_SOMETHING'])

it would be all okay. This is compatible with loading configs from .yml files as well.

一切都会好的。这也与从 .yml 文件加载配置兼容。

回答by Marcel Hymanwerth

There isn't any built-in way to handle this (although actionpack might have a helper for that). I would advise something like this

没有任何内置方法来处理这个问题(尽管 actionpack 可能有一个帮手)。我会建议这样的事情

def to_boolean(s)
  s and !!s.match(/^(true|t|yes|y|1)$/i)
end

# or (as Pavling pointed out)

def to_boolean(s)
  !!(s =~ /^(true|t|yes|y|1)$/i)
end

What works as well is to use 0 and non-0 instead of false/true literals:

同样有效的是使用 0 和非 0 而不是 false/true 文字:

def to_boolean(s)
  !s.to_i.zero?
end

回答by AlexChaffee

ActiveRecord::Type::Boolean.new.type_cast_from_userdoes this according to Rails' internal mappings ConnectionAdapters::Column::TRUE_VALUESand ConnectionAdapters::Column::FALSE_VALUES:

ActiveRecord::Type::Boolean.new.type_cast_from_user根据 Rails 的内部映射执行此操作,ConnectionAdapters::Column::TRUE_VALUES并且ConnectionAdapters::Column::FALSE_VALUES

[3] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("true")
=> true
[4] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("false")
=> false
[5] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("T")
=> true
[6] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("F")
=> false
[7] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("yes")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("yes") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):7)
=> false
[8] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("no")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("no") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):8)
=> false

So you could make your own to_b(or to_boolor to_boolean) method in an initializer like this:

因此,您可以在这样的初始化程序中创建自己的to_b(或to_boolto_boolean)方法:

class String
  def to_b
    ActiveRecord::Type::Boolean.new.type_cast_from_user(self)
  end
end

回答by CWitty

In Rails 5 you can use ActiveRecord::Type::Boolean.new.cast(value)to cast it to a boolean.

在 Rails 5 中,您可以使用ActiveRecord::Type::Boolean.new.cast(value)将其转换为布尔值。

回答by Prodis

You can use wannabe_bool gem. https://github.com/prodis/wannabe_bool

你可以使用wannabe_bool gem。 https://github.com/prodis/wannabe_bool

This gem implements a #to_bmethod for String, Integer, Symbol and NilClass classes.

这个 gem#to_b为 String、Integer、Symbol 和 NilClass 类实现了一个方法。

params[:internal].to_b

回答by socha23

I don't think anything like that is built-in in Ruby. You can reopen String class and add to_bool method there:

我认为 Ruby 中没有内置任何类似的东西。您可以重新打开 String 类并在那里添加 to_bool 方法:

class String
    def to_bool
        return true if self=="true"
        return false if self=="false"
        return nil
    end
end

Then you can use it anywhere in your project, like this: params[:internal].to_bool

然后你可以在你的项目中的任何地方使用它,就像这样: params[:internal].to_bool

回答by user1839842

Perhaps str.to_s.downcase == 'true'for completeness. Then nothing can crash even if stris nil or 0.

也许是str.to_s.downcase == 'true'为了完整性。那么即使str为零或 0也不会崩溃。

回答by d11wtq

Looking at the source code of Virtus, I'd maybe do something like this:

查看Virtus的源代码,我可能会这样做:

def to_boolean(s)
  map = Hash[%w[true yes 1].product([true]) + %w[false no 0].product([false])]
  map[s.to_s.downcase]
end