数组作为ruby中的参数

时间:2013-05-16 04:40:08

标签: ruby

我试图获取所有失败的列表。如果找不到id中的任何一个,则捕获错误消息.Follwoing是一个水豚自动化脚本。

在下面的代码中,异常处理工作正常!

  puts "Verifying Home Page"
      def verifyHomepage(id, successMsg, errorMsg)
       begin   
        page.find(id)
        puts successMsg
       rescue
        puts errorMsg
       end
    end

   verifyHomepage("#logoAnchor", "logo anchor found", "Logo anchor not Found")
   verifyHomepage(".navbar-inner", "Header Bar found", "Header Bar  not Found")
   verifyHomepage(".unstyled", "All Occasions Frame found", "All Occasions Frame not Found")
   verifyHomepage("##easyPrintPromoBox", "Easy Print Frame", "Easy Print Frame not Found")
   verifyHomepage(".tabbable", "l3 Tabs  Featured Occasions/Pairings/ArtistEasy Print Frame", "3 Tabs  Featured Occasions/Pairings/ArtistEasy Print Frame Not found")
   verifyHomepage("##givingCardPromoBox", "Create the perfect gift found", "Create the perfect gift not Found")
   verifyHomepage(".footerr", "Footer Frame found", "Footer Frame found not Found")

我在这里使用不同的verifyHomePage值反复调用param方法7次。

如何将3 params作为array值而不是string值传递。我的意思是 例如:

 verifyHomepage(idArray[],successMsg[],errorMsg[])

2 个答案:

答案 0 :(得分:2)

您可以使用splat运算符将可变数量的参数传递给您的方法,每个参数可以是一个3元素数组。

def verifyHomepage(*args)
  args.each do |a|
    id = a[0]
    successMsg = a[1]
    errorMsg = a[2]
    # process args
  end
end

verifyHomepage(['.footerr', 'Footer Frame found', 'Footer Frame not found'], ['#giving', 'Create the perfect gift', 'not found'])

答案 1 :(得分:1)

你的建议:

verifyHomepage(idArray[],successMsg[],errorMsg[])

是可能的,但是你要维护三个需要保持同步的数组。哈希数组是一种更清洁的方法:

def verifyHomepage(items)
  items.each do |item|
    begin
      page.find(item[:selector])
      puts item[:successMsg]
    rescue
      puts item[:errorMsg]
    end
  end
end

items = [{ :selector => "#logoAnchor",
           :successMsg => "logo anchor found",
           :errorMsg => "Logo anchor not Found"},
         { :selector => ".navbar-inner",
           :successMsg => "Header Bar found",
           :errorMsg => "Header Bar  not Found"},
         { :selector => ".unstyled",
           :successMsg => "All Occasions Frame found",
           :errorMsg => "All Occasions Frame not Found"},
         { :selector => "##easyPrintPromoBox",
           :successMsg => "Easy Print Frame",
           :errorMsg => "Easy Print Frame not Found"},
         { :selector => ".tabbable",
           :successMsg => "l3 Tabs  Featured Occasions/Pairings/ArtistEasy Print Frame",
           :errorMsg => "3 Tabs  Featured Occasions/Pairings/ArtistEasy Print Frame Not found"},
         { :selector => "##givingCardPromoBox",
           :successMsg => "Create the perfect gift found",
           :errorMsg => "Create the perfect gift not Found"},
         { :selector => ".footerr",
           :successMsg => "Footer Frame found",
           :errorMsg => "Footer Frame found not Found"}]

puts "Verifying Home Page"
verifyHomepage(items)