问题
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