-1

I am just wondering what happens to an object when to_s is applied to it with a colon? It is supposed to turn a single letter string into a symbol for a card game. Could someone explain if that is correct? Thanks! Here's an example:

def to_s
    revealed? ? value.to_s : " "
end
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    Please, post text as text, not as photographs of text. This is a website for programmers, not photographers. We want to copy&paste&run your code, not critique your use of color and perspective. https://meta.stackoverflow.com/a/285557/2988 https://idownvotedbecau.se/imageofcode – Jörg W Mittag Nov 09 '21 at 20:50
  • @JörgWMittag Thank you for the correction! I apologize as I am new to the site, won't happen again – hematopoietic Nov 09 '21 at 20:58

2 Answers2

1

Are you referring to the ternary operator?

It's the same as:

if revealed?
  value.to_s
else
 " "
end
Balastrong
  • 4,336
  • 2
  • 12
  • 31
0

This is the ternary operator.

condition ? expression-to-evaluate-if-true : expression-to-evaluate-if-false

Your example is equivalent to:

def to_s
    if revealed?
        value.to_s
    else
        " "
    end
end

In other words, the ? : construct has nothing specifically to do with to_s.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • Yes, I understand now! I had assumed ":" belonged to "to_s", and did not realize that it was equivalent to an else statement for the ternary operator. Thanks Chris! – hematopoietic Nov 09 '21 at 20:53
  • Excellent. It's a nice concise way of writing expressions like this, but be careful and use it judiciously. If you have to ask yourself if you should be using it vs regular if/else, the answer is probably "no." – Chris Nov 09 '21 at 20:56
  • Gotcha, thanks so much for the tip! I'll keep that in mind – hematopoietic Nov 09 '21 at 21:00