String “true” and “false” to boolean

前端 未结 13 846
青春惊慌失措
青春惊慌失措 2020-12-08 18:23

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

13条回答
  •  借酒劲吻你
    2020-12-08 18:52

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

    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:

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

提交回复
热议问题