Ruby:如何将字符串转换为布尔值 [英] Ruby: How to convert a string to boolean
本文介绍了Ruby:如何将字符串转换为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个值,它将是以下四项之一:布尔值true,布尔值false,字符串"true"或字符串"false".我想将字符串转换为布尔值(如果它是字符串),否则将其保持不变.换句话说:
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"应变为true
"true" should become true
假"应变为假
true应该保持为真
true should stay true
假应该保持假
推荐答案
def true?(obj)
obj.to_s.downcase == "true"
end
这篇关于Ruby:如何将字符串转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文