Is there any method to convert boolean variable to

2019-06-13 05:22发布

问题:

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