I want to get the last character in a string MY WAY - 1) Get last index 2) Get character at last index, as a STRING. After that I will compare the string with another, but I won't include that part of code here. I tried the code below and I get a strange number instead. I am using ruby 1.8.7.
Why is this happening and how do I do it ?
line = "abc;" last_index = line.length-1 puts "last index = #{last_index}" last_char = line[last_index] puts last_char
Output-
last index = 3 59
Ruby docs told me that array slicing works this way -
a = "hello there" a[1] #=> "e"
But, in my code it does not.
You can use string. back() to get a reference to the last character in the string. The last character of the string is the first character in the reversed string, so string. rbegin() will give you an iterator to the last character.
UPDATE: I keep getting constant up votes on this, hence the edit. Using [-1, 1]
is correct, however a better looking solution would be using just [-1]
. Check Oleg Pischicov's answer.
line[-1] # => "c"
Original Answer
In ruby you can use [-1, 1]
to get last char of a string. Here:
line = "abc;" # => "abc;" line[-1, 1] # => ";" teststr = "some text" # => "some text" teststr[-1, 1] # => "t"
Explanation: Strings can take a negative index, which count backwards from the end of the String, and an length of how many characters you want (one in this example).
Using String#slice
as in OP's example: (will work only on ruby 1.9 onwards as explained in Yu Hau's answer)
line.slice(line.length - 1) # => ";" teststr.slice(teststr.length - 1) # => "t"
Let's go nuts!!!
teststr.split('').last # => "t" teststr.split(//)[-1] # => "t" teststr.chars.last # => "t" teststr.scan(/.$/)[0] # => "t" teststr[/.$/] # => "t" teststr[teststr.length-1] # => "t"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With