2

I would like to print one of two strings dependently on the condition value in Ruby.

Of course it can be always done in the most classic way:

if a==1 then puts "Yes!" else puts "No!" end

or even

puts (a==1 ? "Yes!" : "No!")

but I'm looking for more Ruby/Python way using lists/arrays. In Python it can be done with:

print ['Yes', 'No'][1==2]

Is there any similar way to achieve this with Ruby? The code above (written in Ruby) doesn't work, because of boolean value as an index and it doesn't work even if I'd try (1==2).to_i...
Any ideas?

7
  • 1
    ['yes', 'no'][(1==2) ? 0 : 1] ? Commented Jan 3, 2016 at 15:28
  • 1
    Personally if you want it short as possible then I can only think of 1 == 2 ? 'yes' : 'no' Commented Jan 3, 2016 at 15:35
  • @NabeelAmjad, actually - yes, you're right, this is also the short one. I was just really curious about the Python way as I mentioned. Commented Jan 3, 2016 at 15:41
  • 2
    You don't need the parentheses in the second code: puts a == 1 ? "Yes!" : "No!". And you still want it shorter? Besides the minimum things that express your information (puts, a == 1, "Yes!", and "No"), there are only two characters extra: ? and :. How can it be shorter? Commented Jan 3, 2016 at 15:41
  • 1
    More craziness: puts ["Yes!", "No!"][[1].index(a) || 1]. Commented Jan 3, 2016 at 17:05

5 Answers 5

5

Provided that your a is numeric, you can do this:

puts ["Yes!", "No!"][a <=> 1]
Sign up to request clarification or add additional context in comments.

3 Comments

Clever! - It makes use of fact that array element at index 1 can be accessed using index -1as well.
Very clever indeed, but I'm not sure I'd like to see something like this in my code :)
Comparable is sufficient.
2

I've never seen python way in ruby world

but you can open class.

class TrueClass
  def to_agreement   # any method name you want
    'Yes'
  end
end

class FalseClass
  def to_agreement
    'No'
  end
end

Or, I suggest use module

module Agreementable
  def to_agreement
    self ? 'Yes' : 'No'
  end
end

TrueClass.include Agreementable
FalseClass.include Agreementable

Above both two way, You can use

true.to_agreement #=> 'Yes'
false.to_agreement #=> 'No'
(1==2).to_agreement #=> 'No'

It is ruby way.

1 Comment

I was rather trying to make my code shorter with some Python-like built-in trick, bro. I hope there is any other way.
2
puts({true => 'Yes', false => 'No'}[a == 1])

Comments

1

puts (if a == 1 then "Yes!" else "No!" end)

Comments

1

You could add to_i method to TrueClass and FalseClass

class TrueClass
    def to_i
        1
    end
end

class FalseClass
    def to_i
        0
    end
end


p ['yes', 'no'][(2==2).to_i]

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.