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]
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]
On Feb 11, 2006, at 6:07 PM, draco draco wrote:
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 G. II
On 2/11/06, draco draco [email protected] wrote:
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]
You can do:
last_char = x[-1,1]
or # possibly too arcane
last_char = x.split(‘’).last
The second has the advantage of being (I think) multibyte-character
safe.
draco draco wrote:
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]
last_char = x[-1,1]
A negative index counts from the right-hand end of the string.
draco draco wrote:
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
Wow 
x[-1,1] looks far more readable than x[x.length-1, x.length-1]
Thanks a lot 
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs