字符串“true”和“false”为布尔值

时间:2011-11-14 10:06:38

标签: jquery ruby-on-rails ruby ruby-on-rails-3

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

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

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

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

但我认为必须采用更加Ruby的方式来解决这个问题!不存在......?

13 个答案:

答案 0 :(得分:129)

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

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

答案 1 :(得分:47)

ActiveRecord提供了一种干净的方法。

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

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

答案 2 :(得分:23)

安全通知

请注意,这个简单形式的答案仅适用于下面列出的其他用例,而不是问题中的答案。虽然大部分是固定的,但是有很多YAML related security vulnerabilities是由于将用户输入加载为YAML而引起的。


我用来将字符串转换为bools的技巧是YAML.load,例如:

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

YAML bool接受了相当多的truthy / falsy字符串:

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

另一个用例

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

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

在命令行中:

$ export ETC_SOMETHING=false

现在由于ENV vars是代码内部的字符串,config.etc.something的值将是字符串"false",并且它会错误地评估为true。但如果你喜欢这样:

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

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

答案 3 :(得分:16)

没有任何内置的方法来处理这个问题(虽然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

也可以使用0和非0而不是false / true文字:

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

答案 4 :(得分:7)

ActiveRecord::Type::Boolean.new.type_cast_from_user根据Rails的内部映射ConnectionAdapters::Column::TRUE_VALUESConnectionAdapters::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

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

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

答案 5 :(得分:5)

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

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

params[:internal].to_b

答案 6 :(得分:5)

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

答案 7 :(得分:3)

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

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

然后您可以在项目的任何位置使用它,例如:params[:internal].to_bool

答案 8 :(得分:2)

查看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

答案 9 :(得分:2)

可能str.to_s.downcase == 'true'表示完整性。即使str为零或0,也不会崩溃。

答案 10 :(得分:1)

您可以考虑仅将internal附加到您的网址,如果确实如此,那么如果未选中该复选框并且您没有追加它params[:internal]将是nil,在Ruby中评估为false。

我对你正在使用的特定jQuery并不熟悉,但是除了手动构建URL字符串之外,还有更简洁的方法来调用你想要的东西吗?您看过$get$ajax了吗?

答案 11 :(得分:1)

您可以添加String类以使用to_boolean方法。然后你可以做真正的&#39; .to_boolean或&#39; 1&#39; .to_boolean

class String
  def to_boolean
    self == 'true' || self == '1'
  end
end

答案 12 :(得分:-4)

我很惊讶没有人发布这个简单的解决方案。那就是如果你的字符串是&#34; true&#34;或&#34;假&#34;。

def to_boolean(str)
    eval(str)
end
相关问题