Ruby - Convert Integer to String

前端 未结 7 1176
孤独总比滥情好
孤独总比滥情好 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条回答
  • I believe this is changing in Ruby 1.9 such that "asdf"[2] yields "d" rather than the character code

    0 讨论(0)
  • 2021-01-17 11:32

    Or you can convert the integer to its character value:

    a[0].chr
    
    0 讨论(0)
  • 2021-01-17 11:36

    You want a[0,1] instead of a[0].

    0 讨论(0)
  • 2021-01-17 11:44

    The [,] operator returns a string back to you, it is a substring operator, where as the [] operator returns the character which ruby treats as a number when printing it out.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2021-01-17 11:49

    I think each_char or chars describes better what you want.

    irb(main):001:0> a = "0123"
    => "0123"
    irb(main):002:0> Array(a.each_char)
    => ["0", "1", "2", "3"]
    irb(main):003:0> puts Array(a.each_char)
    0
    1
    2
    3
    => nil
    
    0 讨论(0)
提交回复
热议问题