简体   繁体   中英

How can I get Ruby to treat the index of a string as a character (rather than the ASCII code)?

I am checking to see if the last character in a directory path is a '/'. How do you get ruby to treat the specific index of a string as a character rather than the associated ASCII code?

For example the following always returns false :

dir[dir.length - 1] == '/'

This is because dir[dir.length - 1] returns the ASCII code 47 (rather than '/').

Any thoughts on how to interpret 47 as '/'? Or is there a completely different way to handle this in the first place?

Thanks.

You have to be a bit careful, because the behavior has changed from Ruby 1.8 and Ruby 1.9.

# In Ruby 1.8:
"hello"[0] == 104

# In Ruby 1.9:
"hello"[0] == "h"

# In both versions:
"hello"[0] == ?h
"hello"[0, 1] == "h"

In general, if you just want to test for equality with a character, you can use the ?x to signify the character x (which will be the ascii code in 1.8 and the string in 1.9), or else use the range form by giving an explicit length. This is assuming you're dealing with ascii only. For unicode, you should probably be using Ruby 1.9.

From your example, the nicest form is probably dir[-1] == ?/ , or if using Rails (or activesupport), you might prefer dir.ends_with? '/' dir.ends_with? '/'

You can interpret 47 as '/' with 47.chr which returns => "/" As a side note, you can use dir[-1] to return the last character, rather than dir[dir.length-1]

So, this will work in either ruby 1.8 or 1.9:

dir[-1].chr == '/'

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