Thursday, April 21, 2011

how to do the following in ruby ?

I need to grab a string like

"/html/body/a"

i need to check the last portion, in this case "a" after the final "/"

how can i do this ? how can i regex match for the last item after the final "/" ?

From stackoverflow
  • x = "/html/body/a"
    x.split("/").last  # => "a"
    
  • Regex? Not sure, but what's wrong with

    my_string.split("/").last # Maybe you want some error checking here, I don't know.
    
  • If you want to use regexp, this would be it:

    mystring = "/html/body/a"
    if mystring =~ /([^\/]+)$/
        last_part = $1
    end
    
    David Seiler : +1 for actually answering the question posed :)

0 comments:

Post a Comment