如何将这个链接与Rails交换?

时间:2021-11-24 00:04:19

I am trying to take this link..

我正试着利用这个链接。

http://www.youtube.com/watch?v=4lzi_3SM9-o

And turn it into this:

把它变成这样

http://www.youtube.com/v/4lzi_3SM9-o

To do this I need some way to capture watch?v= and switch it with v/

要做到这一点,我需要一些方法来捕捉手表?v=和v/交换

And I would like to accomplish this in my model with def tube_link

我想用def tube_link在我的模型中实现这一点

Any ideas?

什么好主意吗?

3 个解决方案

#1


3  

No need for regex, just use string replacement:

不需要regex,只需使用字符串替换:

url["watch?v="] = "v/"

But be warned that you might get an index error if you index on something that isn't in the string. (See here for more information.)

但是要注意的是,如果索引的对象不在字符串中,那么可能会出现索引错误。(更多信息请参见这里。)

Edit: Something like this might be more readable (and more reliable):

编辑:这样的东西可能更容易读(更可靠):

newUrl = oldUrl.gsub("watch?v=", "v/")

#2


4  

"http://www.youtube.com/watch?v=4lzi_3SM9-o".gsub("watch?v=", "v/")

#3


2  

You should replace double quotes with single quote. It will save your time

你应该用单引号代替双引号。这会节省你的时间

t1 = Time.now
for i in 1..100000
  "http://www.youtube.com/watch?v=4lzi_3SM9-o".gsub("watch\?v=", "v/")
end
t2 = Time.now 
p t2-t1

>ruby test.rb
1.173

t1 = Time.now
for i in 1..100000
"http://www.youtube.com/watch?v=4lzi_3SM9-o".gsub('watch\?v=', 'v/')
end
t2 = Time.now 
p t2-t1

>ruby test.rb
0.406

1.173 Vs. 0.406

1.173与0.406

#1


3  

No need for regex, just use string replacement:

不需要regex,只需使用字符串替换:

url["watch?v="] = "v/"

But be warned that you might get an index error if you index on something that isn't in the string. (See here for more information.)

但是要注意的是,如果索引的对象不在字符串中,那么可能会出现索引错误。(更多信息请参见这里。)

Edit: Something like this might be more readable (and more reliable):

编辑:这样的东西可能更容易读(更可靠):

newUrl = oldUrl.gsub("watch?v=", "v/")

#2


4  

"http://www.youtube.com/watch?v=4lzi_3SM9-o".gsub("watch?v=", "v/")

#3


2  

You should replace double quotes with single quote. It will save your time

你应该用单引号代替双引号。这会节省你的时间

t1 = Time.now
for i in 1..100000
  "http://www.youtube.com/watch?v=4lzi_3SM9-o".gsub("watch\?v=", "v/")
end
t2 = Time.now 
p t2-t1

>ruby test.rb
1.173

t1 = Time.now
for i in 1..100000
"http://www.youtube.com/watch?v=4lzi_3SM9-o".gsub('watch\?v=', 'v/')
end
t2 = Time.now 
p t2-t1

>ruby test.rb
0.406

1.173 Vs. 0.406

1.173与0.406