Ruby 获取url参数的方法

第一种

参数:url,参数名
返回:参数内容

def getURLParam(url,param)
        hash={}
        hash.default=''
        if url.index('?')
                str=url.split('?')[1]
                if str.split('&')
                        array=str.split('&')
                        array.each{
                                |item| hash[item.split('=')[0]]=item.split('=')[1]
                        }
                end
        end
        return hash[param]
end

示例:

url='https://www.baidu.com?a=1&b=2&c=3'
puts getURLParam(url,'b') // 2

第二种

参数:url
返回:hash

def getURLParam(url)
        hash={}
        hash.default=''
        if url.index('?')
                str=url.split('?')[1]
                if str.split('&')
                        array=str.split('&')
                        array.each{
                                |item| hash[item.split('=')[0]]=item.split('=')[1]
                        }
                end
        end
        return hash
end

示例:

url='https://www.baidu.com?a=1&b=2&c=3'
hash=getURLParam(url)
puts hash // {"a"=>"1", "b"=>"2", "c"=>"3"}

猜你喜欢

转载自blog.csdn.net/weixin_42473019/article/details/104022526