【问题标题】:parse the parametes of a function string in Ruby在 Ruby 中解析函数字符串的参数
【发布时间】:2013-02-28 03:38:26
【问题描述】:

感谢您的宝贵时间!

我得到一个字符串,看起来像这样:

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);

我想获取这个函数字符串的参数,并将它们存储在不同的变量中。然后我想到的是用string.split(",")分割这个字符串,然后得到它的每一部分。

但是如果参数里面有逗号,说这个"Body=xxxx,xxxx",上面的方法就错了。

那么有一些优雅而整洁的方法来处理它吗?再次感谢!

【问题讨论】:

    标签: ruby string


    【解决方案1】:

    您可以使用parameters 执行此操作。下面的示例返回一个hash,其键是局部变量名,值是方法调用中传递的值。

    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"}
    

    【讨论】:

    • 太棒了!这真的很有帮助。这里的另一篇文章可能有助于理解这里的代码(老实说,这些代码超出了我对 Ruby 的了解)is-there-a-way-to-access-method-arguments-in-ruby。另外,由于我处理的函数是一个字符串,所以在我的例子中我使用h = eval string。谢谢@Ashish
    • @user1476512 感谢您添加该链接。看来,即使是我在遇到与您类似的问题时也提到了该答案。
    【解决方案2】:

    我认为这取决于您的字符串的格式。

    如果如您在上面给出的那样,那么使用string.split(不指定分隔符)将起作用,因为它将分割字符串,在您的情况下,空格自然落在不同的“参数”之间。

    如果您的字符串中根本没有空格,例如:

    string = 'web_custom_request("pricing_approval","Method=GET","Body=xxxx,xxxx")'
    

    那么您可以使用正则表达式来查找引号之间的部分,例如string.scan(/"([^"]*)"/)

    它给出了以下匹配组:

    [["pricing_approval"], ["Method=GET"], ["Body=xxxx,xxxx"]]
    

    【讨论】:

    • 该死!以为我说得太简单了。
    • 在这种情况下(同样在没有空格的情况下)可能会尝试拆分逗号直接紧邻引号的字符串,即string.split(/",/)
    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2015-04-22
    相关资源
    最近更新 更多