Mega Code Archive

 
Categories / Ruby / String
 

Use string as array

s = 'hello'    puts s[0]           # 104: the ASCII character code for the first character 'h' puts s[s.length-1]  # 111: the character code of the last character 'o' puts s[-1]          # 111: another way of accessing the last character puts s[-2]          # 108: the second-to-last character puts s[-s.length]   # 104: another way of accessing the first character puts s[s.length]    # nil: there is no character at that index