params[:svn_path]
このようなURLを返しています
http://svn.repos.mywebsite.com/testingtitle.documents
ここで、URL の最後の部分のみを取得する必要がありtestingtitle
ます。
どうやって手に入れるの?
前もって感謝します
params[:svn_path]
このようなURLを返しています
http://svn.repos.mywebsite.com/testingtitle.documents
ここで、URL の最後の部分のみを取得する必要がありtestingtitle
ます。
どうやって手に入れるの?
前もって感謝します
rubyのUriモジュールが使える
uri = URI.parse("http://svn.repos.mywebsite.com/testingtitle.documents")
path = uri.path #"/testingtitle.documents"
path_with_no_slash = path.gsub("/", "") #"testingtitle.documents"
array = path_with_no_slash.split(".") #["testingtitle", "documents"]
result = array[0] #"testingtitle"
使用できますFile.basename
; 例えば
url = "http://svn.repos.mywebsite.com/testingtitle.documents"
ext = File.extname(url)
result = File.basename(url, ext)
basename
ファイル拡張子の削除を処理するための2番目の引数。result
望ましい結果を保持します。
期待どおりの結果を得るには、正規表現を使用する必要があります。
これが良い例です。
適切なURIパーサーを使用 -
これにより、あなたが述べたように、URL の最後の部分が得られます。
require 'uri'
url = "http://svn.repos.mywebsite.com/testingtitle.documents"
last_part = URI(url).path.split('/').last # => testingtitle.documents
ただし、提供した出力は、最後の部分でもう少し操作する必要があります。つまり、分割します.
last_part.split('.').first # => testingtitle
シンプルな文字列操作 -
url = "http://svn.repos.mywebsite.com/testingtitle.documents"
url.split('/').last.split('.').first # => testingtitle
これを試して:
params[:svn_path].match(/.*\.com\/(.*)\..*$/)[1]
1.9.3p194 :009 > params[:svn_path].match(/.*\.com\/(.*)\..*$/)[1]
=> "testingtitle"
URI
この URL を解析するために使用できます。
url = URI.parse('http://svn.repos.mywebsite.com/testingtitle.documents')
これらの変数を持つオブジェクトが得られます。
url.instance_variables #> [ :@scheme, :@user, :@password, :@host, :@port, :@path, :@query, :@opaque, :@registry, :@fragment, :@parser ]
path
次に、次のようにコンポーネントで単純な正規表現を使用します。
url.path.match(/\w+/) #> #<MatchData "testingtitle">
これは、任意の単語文字 (/ または . を除く) の最初の出現に一致します。
Regexp
+groups
url = 'http://svn.repos.mywebsite.com/testingtitle.documents'
puts url.match(/com\/([a-z]+)/)[1]
#=> testingtitle