Why does β€œ? B” mean β€œb” in Ruby?

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

I looked at the example above and tried to figure out:

  • How does "? B" mean the character "b"?
  • Why is this necessary? - I can’t just write this:

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

+4
source share
4 answers

Ed Swangren :? returns character character code.

Not in Ruby 1.9. Starting from 1.9 ?a returns 'a'. See Here: Son of 10 Things You Need to Know About 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 complete description of the changes in Ruby 1.9 .

Other editing: note that now you can use 'a'.ord if you want the string with the conversion number you get in 1.8 through ?a 'a'.ord

+10
source

This change is due to Ruby 1.9 UTF-8 updates.

Ruby version 1.8 ? Worked with single-byte characters only. In 1.9, they updated everything to work with multibyte characters. The problem is that it is not clear which integer should return from ?€ .

They solved this by changing what he returns. In 1.9, all of the following are singleton strings and are equivalent:

 ?€ '€' "€" "\u20AC" ?\u20AC 

They were supposed to drop the notation, IMO, and not (somewhat randomly) change the behavior. However, this is not even officially out of date.

+5
source

? returns the character code of a character. Here is the corresponding article for you.

0
source

In some languages ​​(Pascal, Python), characters do not exist: they are just strings of length 1.

In other languages ​​(C, Lisp), characters exist and have clear syntax, for example, 'x' or # \ x.

Ruby was mostly on the "no character" side, but at times it didn't seem to be completely sure about that choice. If you want characters to be a data type, Ruby already assigns the value "and", so what? X looks just as smart as any other option for char literals.

For me, it's just a matter of what you mean. You could also say foo [0] = 98, but you use an integer when you really mean the character. Using a string when you mean a character looks equally strange to me: the set of operations it supports is almost completely different. One of them is the sequence of the other. You would not force Math.sqrt to take a list of numbers and just look only at the first. You would not miss an β€œinteger” from the language just because you already support the β€œinteger list”.

(Actually, Lisp 1.0 did just that - church numbers for everything!), But the performance was terrible, so this was one of the great achievements of Lisp 1.5 that made it suitable for use as a real language, back in 1962. )

0
source

All Articles