将两个不同的字符串与Ruby on Rails中的相同部分进行比较

时间:2018-06-19 09:23:47

标签: ruby-on-rails ruby url

我需要接受网址并将其与其他网址进行比较。两个URL都具有相同的开始但不同的结束动态变化。我接受类似+-----------------------------------------------------------------------------+ | NVIDIA-SMI 390.30 Driver Version: 390.30 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 Tesla K80 Off | 0000752C:00:00.0 Off | 2 | | N/A 39C P8 25W / 149W | 0MiB / 11441MiB | 0% Default | +-------------------------------+----------------------+----------------------+ 之类的内容,需要与https://url.com/something_else进行比较,检查此部分是否在收到的网址中没有https://url.com/。我怎么能在Rails中做到这一点?

2 个答案:

答案 0 :(得分:7)

您可以使用URI模块https://docs.ruby-lang.org/en/2.1.0/URI.html

uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
uri.host
#=> "foo.com"

答案 1 :(得分:5)

请尝试如下所示的URI模块:-

require 'uri'

uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
#=> #<URI::HTTP:0x00000000b14880
      URL:http://foo.com/posts?id=30&limit=5#time=1305298413>
uri.scheme
#=> "http"
uri.host
#=> "foo.com"
uri.path
#=> "/posts"
uri.query
#=> "id=30&limit=5"
uri.fragment
#=> "time=1305298413"

uri.to_s
#=> "http://foo.com/posts?id=30&limit=5#time=1305298413"

谢谢:)