简体   繁体   中英

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 CI 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?

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.

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

>> 'c'.class                                                            
=> String

Yes. While in C a string is represented as C-String, which is basically a zero-terminated array of characters, a String in Ruby is a class that stores its content in a more complex way. You can extract any part of it to a new String, and Ruby probably won't give you lower access to it. In C you get direct access to the memory of it, Ruby is a lot more abstract than that.

Yes, there is no char class in Ruby, there is only String. (Note that char is defined as 1 byte in the C standard, but that is not the case for unicode characters).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM