创建阵列选项的所有排列的问题

时间:2013-12-27 00:07:41

标签: arrays if-statement permutation capybara-webkit

不确定我在这里缺少什么,尝试创建一个新的数组,其中包含大小和颜色数组的所有可能选项。将其用作指南:https://stackoverflow.com/a/5227021/2964789。所需的输出应为:Black-L,Black-M,Black-S,Black-XL,Black-XXL,RedL,Red-M,Red-S,Red-XL,Red-XXL

require "capybara/dsl"
require "spreadsheet"
require "fileutils"
require "open-uri"
include Capybara::DSL


Capybara.run_server = false
Capybara.default_driver = :selenium
Capybara.default_selector = :xpath
Spreadsheet.client_encoding = 'UTF-8'


visit "http://www.example.com/sexy-women-pencil-dress-see-through-mesh-stripes-backless-bodycon-slim-party-clubwear-g0376.html"

if page.has_selector?("//dd[1]//select[contains(@name, 'options')]//*[@price='0']") and page.has_no_xpath?("//dd[2]//select[contains(@name, 'options')]//*[@price='0']")
optionchoice = page.all("//dd[1]//select[contains(@name, 'options')]//*[@price='0']")
options = optionchoice.collect(&:text).join(', ')
elsif page.has_selector?("//dd[2]//select[contains(@name, 'options')]//*[@price='0']") and page.has_no_xpath?("//dd[1]//select[contains(@name, 'options')]//*[@price='0']")
optionchoice = page.all("//dd[2]//select[contains(@name, 'options')]//*[@price='0']")
options = optionchoice.collect(&:text).join(', ')
else page.has_selector?("//dd[1]//select[contains(@name, 'options')]//*[@price='0']") and page.has_selector?("//dd[2]//select[contains(@name, 'options')]//*[@price='0']")
  colorchoice = page.all("//dd[1]//select[contains(@name, 'options')]//*[@price='0']")
  colors = colorchoice.collect(&:text).join(', ')

  sizechoice = page.all("//dd[2]//select[contains(@name, 'options')]//*[@price='0']")
  sizes = sizechoice.collect(&:text).join(', ')

  combinedchoice = [[colors],[sizes]]
  options = combinedchoice.each.product(*combinedchoice[1..-1]).map(&:join)

end

puts options

1 个答案:

答案 0 :(得分:1)

假设您有2个数组,颜色和大小:

    colors = ["Black", "Red"]
    sizes = ["L", "M", "S", "XL", "XXL"]

要打印包含所有产品的数组(斜杠之间):

    ["Black-L","Black-M","Black-S","Black-XL","Black-XXL","Red-L","Red-M","Red-S","Red-XL","Red-XXL"]

类型:

    p colors.product(sizes).map { |x| x.join("-") }