Is there any method to convert boolean variable to integer in ruby

早过忘川 提交于 2019-12-08 11:48:17

问题


I have a ruby variable 'is_published'. I want to convert the value in 'is_published' to integer. Is there any method in ruby to do that?

if is_published == true
  is_published = 1
else
  is_published = 0
end

The above code works perfectly. Please help if there is any way to do this in a single line code.


回答1:


class TrueClass; def to_i; 1; end; end
class FalseClass; def to_i; 0; end; end



回答2:


# using logical operators
is_published = is_published && 1 || 0

# using ternary operator
is_published = is_published ? 1 : 0


来源:https://stackoverflow.com/questions/27396547/is-there-any-method-to-convert-boolean-variable-to-integer-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!