Getting last character from a string

D

draco draco

Hello
I'm new to Ruby. I've a simple question.
Is there a more readable way to get last character from string than this
one? :

x = "text"
last_char = x[x.length-1, x.length-1]
 
J

James Edward Gray II

Hello
Hello.

I'm new to Ruby.

Welcome then.
I've a simple question.
Is there a more readable way to get last character from string than
this
one? :

x = "text"
last_char = x[x.length-1, x.length-1]

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 that:

"test"[-1, 1] # => "t"

Hope that helps.

James Edward Gray II
 
W

Wilson Bilkovich

Hello
I'm new to Ruby. I've a simple question.
Is there a more readable way to get last character from string than this
one? :

x =3D "text"
last_char =3D x[x.length-1, x.length-1]

You can do:
last_char =3D x[-1,1]
or # possibly too arcane
last_char =3D x.split('').last

The second has the advantage of being (I think) multibyte-character safe.
 
W

William James

draco said:
Hello
I'm new to Ruby. I've a simple question.
Is there a more readable way to get last character from string than this
one? :

x = "text"
last_char = x[x.length-1, x.length-1]

"abc"[ -1..-1 ]

"abc".slice(-1,1)

"abc".slice(-1).chr

"abc"[ /.$/ ]

"abc".reverse[0,1]

"abc".split('').pop

class String
def last
self[-1,1]
end
end

"abc".last
 
D

draco draco

Wow :)

x[-1,1] looks far more readable than x[x.length-1, x.length-1]

Thanks a lot :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top