Forum: Ruby Getting last character from a string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5a428b00d61b0c3eee4fb4c1df3bc97a?d=identicon&s=25 Marek Zdankiewicz (draco)
on 2006-02-12 01:07
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]
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-02-12 01:12
(Received via mailing list)
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 Gray II
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2006-02-12 01:17
(Received via mailing list)
On 2/11/06, draco draco <thedraco@go2.pl> 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.
37a3c73ffbf864e4b28f7f2384ee12ce?d=identicon&s=25 Timothy Hunter (tim-hunter)
on 2006-02-12 01:18
(Received via mailing list)
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.
2ee1a7960cc761a6e92efb5000c0f2c9?d=identicon&s=25 William James (Guest)
on 2006-02-12 10:08
(Received via mailing list)
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
5a428b00d61b0c3eee4fb4c1df3bc97a?d=identicon&s=25 Marek Zdankiewicz (draco)
on 2006-02-12 10:34
Wow :)

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

Thanks a lot :)
This topic is locked and can not be replied to.