0

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.

7
  • May be like this: is_published = is_published? 1: 0; I don't know the syntax of ruby, I use this in js Commented Dec 10, 2014 at 8:48
  • 4
    You can use the conditional operator(? :). "is_published ? 1 : 0" is answer for you. Commented Dec 10, 2014 at 8:52
  • 1
    is_published = (is_published && 1) || (is_published || 0) is another way. Commented Dec 10, 2014 at 9:05
  • 1
    That equals (is_published && 1) || 0, @CarySwoveland Commented Dec 10, 2014 at 9:32
  • 1
    @spickermann, yes, that's better. My preference: is_published ? 1 : 0. Boring, perhaps, but reads the best. Commented Dec 10, 2014 at 10:01

2 Answers 2

5
class TrueClass; def to_i; 1; end; end
class FalseClass; def to_i; 0; end; end
Sign up to request clarification or add additional context in comments.

4 Comments

Egad, Egor! That's all I wanted to say.
This is probably too global for my taste :)
Accepting this answer, but i would like to use is_published = (is_published && 1) || (is_published || 0)
I agree with @SergioTulentsev. Is the reason for doing this that you're using a database which stores booleans as 0 & 1 (eg MySQL)? If so then it would be better to hook into Rails' db "translators" to do this - then it will be db-agnostic.
2
# using logical operators
is_published = is_published && 1 || 0

# using ternary operator
is_published = is_published ? 1 : 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.