R – Why does “?b” mean ‘b’ in Ruby

rubystring

"foo"[0] = ?b # "boo"

I was looking at the above example and trying to figure out:

  1. How "?b" implies the character 'b'?
  2. Why is it necessary? – Couldn't I just write this:

    "foo"[0] = 'b' # "boo"

Best Solution

Ed Swangren: ? returns the character code of a character.

Not in Ruby 1.9. As of 1.9, ?a returns 'a'. See here: Son of 10 things to be aware of in Ruby 1.9!

telemachus ~ $ ~/bin/ruby -v
ruby 1.9.1p0 (2009-01-30 revision 21907) [i686-linux]
telemachus ~ $ ~/bin/ruby -e 'char = ?a; puts char'
a
telemachus ~ $ /usr/bin/ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]
telemachus ~ $ /usr/bin/ruby -e 'char = ?a; puts char'
97

Edit: A very full description of changes in Ruby 1.9.

Another edit: note that you can now use 'a'.ord if you want the string to number conversion you get in 1.8 via ?a.