Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 'c' said to be a character or a string in Ruby - or both?

char hello[] = "hello"; #C
hello = ['h', 'e', 'l', 'l', 'o'] #Ruby

If I output the class of hello[0] in Ruby, it says "String". This is because single quoted Strings exist in Ruby and there does not seem to be the notion of a char type. The other day I said to my coworker that he had an array of characters and he said "no I don't, I have an array of Strings". Nitpicky, yes, but technically perhaps he is correct. Coming from the world of C I tend not to think of a single character as a String. Is it agreed that the hello array above is an array of Strings rather than an array of characters?

like image 385
parsnip Avatar asked Apr 05 '09 20:04

parsnip


2 Answers

In C, a character is distinct from a string (which is an array of characters). Ruby does not have an individual character type. Strings can hold any number of characters, and Fixnums can hold the ASCII value for a character and be converted to a printable string containing that character with the #chr method.

The difference between the single-quote and double-quote string syntax in Ruby has to do with how much preprocessing (interpolation, for example) is done on the string.

like image 52
Chuck Avatar answered Oct 06 '22 02:10

Chuck


Your coworker would be right, Ruby doesn't seem to have any kind of Character class.

>> 'c'.class                                                            
=> String
like image 42
Turnor Avatar answered Oct 06 '22 02:10

Turnor