Alve
Alve

Reputation: 1465

How to get part of string after some word with Ruby?

I have a string containing a path:

/var/www/project/data/path/to/file.mp3

I need to get the substring starting with '/data' and delete all before it. So, I need to get only /data/path/to/file.mp3.

What would be the fastest solution?

Upvotes: 3

Views: 6971

Answers (4)

Xiaodan Mao
Xiaodan Mao

Reputation: 1706

Using regular expression is a good way. Though I am not familiar with ruby, I think ruby should have some function like "substring()"(maybe another name in ruby).

Here is a demo by using javascript:

var str = "/var/www/project/data/path/to/file.mp3";
var startIndex = str.indexOf("/data");
var result = str.substring(startIndex );

And the link on jsfiddle demo

I think the code in ruby is similar, you can check the documentation. Hope it's helpful.

Upvotes: 1

user904990
user904990

Reputation:

could be as easy as:

string = '/var/www/project/data/path/to/file.mp3'

path = string[/\/data.*/]

puts path
=> /data/path/to/file.mp3

Upvotes: 3

QuarK
QuarK

Reputation: 2536

Please try this:

"/var/www/project/data/path/to/file.mp3".scan(/\/var\/www(\/.+)*/)

It should return you all occurrences.

Upvotes: -1

megas
megas

Reputation: 21791

'/var/www/project/data/path/to/file.mp3'.match(/\/data.*/)[0]
=> "/data/path/to/file.mp3"

Upvotes: 6

Related Questions