Ruby - Convert Integer to String

前端 未结 7 1179
孤独总比滥情好
孤独总比滥情好 2021-01-17 11:28

In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I\'m seeing their ASCII values instead:

<         


        
7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 11:48

    To summarize:

    This behavior will be going away in version 1.9, in which the character itself is returned, but in previous versions, trying to reference a single character of a string by its character position will return its character value (so "ABC"[2] returns 67)

    There are a number of methods that return a range of characters from a string (see the Ruby docs on the String slice method) All of the following return "C":

    "ABC"[2,1] 
    "ABC"[2..2]
    "ABC".slice(2,1)
    

    I find the range selector to be the easiest to read. Can anyone speak to whether it is less efficient?

提交回复
热议问题