ZK Zhao
ZK Zhao

Reputation: 21533

Ruby: get string between strings?

I want to get the 3stars from http://images.penguinmagic.com/images/3stars.gif How can I do it? Can it be done elegantly without using regex?

I can do it using split 2 times, but think this is quite bad code.

Upvotes: 1

Views: 58

Answers (2)

You could also use rpartition:

url.rpartition('.')[0].rpartition('/')[2]

But I don't see that much of a problem with the 'bad code' of doing two splits or even using regex, unless you're uncomfortable with regexp in general, in which case this would be a good chance to start learning about them.

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

One easy option is :

url = "http://images.penguinmagic.com/images/3stars.gif"
File.basename(url, File.extname(url)) # => "3stars"

Upvotes: 4

Related Questions