【问题标题】:issues with creating all permutations of array options创建数组选项的所有排列的问题
【发布时间】:2014-01-14 14:06:57
【问题描述】:

不确定我在这里缺少什么,尝试创建一个新数组,其中包含大小和颜色数组的所有可能选项(当两者都存在时)。以此为指导: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

【问题讨论】:

  • 下次删除不需要的代码,输入清楚。

标签: arrays if-statement permutation capybara-webkit


【解决方案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("-") }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多