Question

I build the array here:

  def initialize
    @names = []
  end

@names << page.all('//*[@id="USERS_AVAIL"]/option').map {|result| result.text.split(", ")}

later on I'm trying to compile and visit url's by iterating through the names array like so:

@names.each do |name|
                  visit "https://example.com/k=#{name}&tpe=1"
end

Some puts statements show me that the each method is calling every element of the array all at once instead of iterating as intended. I.E.: "https://example.com/k=#{[[%22Adviento%22,%20%22Justin%22],%20[%22Asamoah%22,%20%22Nathan%22],%20[%22Baughman%22,%20%22Zachary%22],}&tpe=1". @names.length has a count of only 4 but a puts of the @names array shows the proper output? I'm not sure what could be wrong, thanks in advance for any assist.

Was it helpful?

Solution

Replace << with +=. The << is inserting the entire array as a single element of its own, whereas += will concatenate the array, which seems to be your intention.

For example:

a = [1,2,3]
# => [1, 2, 3]
a << [4,5,6]
# => [1, 2, 3, [4, 5, 6]] # WRONG

a = [1,2,3]
# => [1, 2, 3]
a += [4,5,6]
# => [1, 2, 3, 4, 5, 6] # CORRECT

Try:

@names += page.all('//*[@id="USERS_AVAIL"]/option')
          .map { |r| r.text.split(',').map(&:strip) }.flatten

If the quotes are in the literal form %22 and you want to capture the strings in between them:

@names += page.all('//*[@id="USERS_AVAIL"]/option')
          .map { |r| r.text.scan(/%22([^%]+)%22/) }.flatten
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top