在Ruby中解析函数字符串的参数
谢谢你的时间 我得到一个字符串,看起来像这样:在Ruby中解析函数字符串的参数,ruby,string,Ruby,String,谢谢你的时间 我得到一个字符串,看起来像这样: web_custom_request("pricing_approval", "URL=http://loanoriginationci:8080/ro-web/service/pricing/task/list/pricing_approval?uniqueId=1362015883531", "Method=GET", "Resource=0", "RecContentType=text/xml", "R
web_custom_request("pricing_approval",
"URL=http://loanoriginationci:8080/ro-web/service/pricing/task/list/pricing_approval?uniqueId=1362015883531",
"Method=GET",
"Resource=0",
"RecContentType=text/xml",
"Referer=http://loanoriginationci:8080/MAUIWeb/MAUIShell.swf/[[DYNAMIC]]/6",
"Snapshot=t76.inf",
"Mode=HTTP",
LAST);
我想得到这个函数字符串的参数,并将它们存储在不同的变量中。然后我想到的是用字符串拆分这个字符串。拆分(“,”
),然后得到它的每一部分
但是如果参数中有一个逗号,就说这个“Body=xxxx,xxxx”
上面的方法是错误的
那么,有什么优雅而整洁的方法来处理它吗?再次感谢 我认为这取决于字符串的格式 如果如上所述,则使用
string.split
(不指定delimeter)将起作用,因为它将在空白处分割字符串,在您的情况下,空白自然位于不同的“参数”之间
如果字符串中没有空格,例如:
string = 'web_custom_request("pricing_approval","Method=GET","Body=xxxx,xxxx")'
然后可以使用正则表达式查找引号之间的部分,例如string.scan(/“([^”]*)”/)
这将提供以下匹配组:
[["pricing_approval"], ["Method=GET"], ["Body=xxxx,xxxx"]]
您可以使用。下面的示例返回一个散列
,其键是本地变量名,值是在方法调用中传递的值
def web_custom_request(a,b,c,d,e,f,g,h,i)
Hash[*method(__method__).parameters.map { |arg| arg[1] }.map { |arg| [arg.to_s, "#{eval arg.to_s}"] }.flatten]
end
h = web_custom_request("pricing_approval",
"URL=http://loanoriginationci:8080/ro-web/service/pricing/task/list/pricing_approval?uniqueId=1362015883531",
"Method=GET",
"Resource=0",
"RecContentType=text/xml",
"Referer=http://loanoriginationci:8080/MAUIWeb/MAUIShell.swf/[[DYNAMIC]]/6",
"Snapshot=t76.inf",
"Mode=HTTP",
"LAST");
puts h # {"a"=>"pricing_approval", "b"=>"URL=http://loanoriginationci:8080/ro-web/service/pricing/task/list/pricing_approval?uniqueId=1362015883531", "c"=>"Method=GET", "d"=>"Resource=0", "e"=>"RecContentType=text/xml", "f"=>"Referer=http://loanoriginationci:8080/MAUIWeb/MAUIShell.swf/[[DYNAMIC]]/6", "g"=>"Snapshot=t76.inf", "h"=>"Mode=HTTP", "i"=>"LAST"}
该死!我觉得这听起来太简单了。在这种情况下(同样在没有空格的情况下),可能会尝试拆分逗号直接位于引号旁边的字符串,即
string。拆分(/“,/)
。太好了!这真的很有帮助。这里的另一篇文章可能有助于理解这里的代码(老实说,这些代码超出了我对Ruby的了解)。另外,由于我处理的函数是一个字符串,所以我在本例中使用h=eval string
。谢谢@Ashish@user1476512谢谢你添加这个链接。看来,即使是我在面对与你类似的问题时也提到了这个答案。