Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `?n` differ from `'n'`? [duplicate]

Chris Pine's How to Program mentions that the following:

?T

should return 84. When I run it, it returns "T". My suspicion is that there is a version difference. My guess is that ? is an Array or String method, but I cannot find documentation. What does ?T do?

like image 517
notthehoff Avatar asked Feb 15 '23 06:02

notthehoff


1 Answers

In this context, ? with a character is a literal single character string. Therefore ?T is the String "T" and puts ?T is the same as puts "T" You can throw it into IRB to check it out:

1.9.3p429 :002 > ?T
 => "T" 
1.9.3p429 :001 > ?T.class
 => String 
1.9.3p429 :003 > puts ?T
T
 => nil

Related Existing SO Questions and Answers:

  • https://stackoverflow.com/a/1878406/504685
  • What does the unary question mark (?) operator do?

Edit to add: Per a comment on the answer linked above this might have been a change in ruby 1.9 to return a single character String instead of the ASCII character value. (which the ASCII value of T is 84 )

1.9.3p429 :006 > ?T.ord
 => 84 
like image 98
Charlie Avatar answered Feb 16 '23 20:02

Charlie