How to 'puts' a number list of items in the array using an 'until' loop

百般思念 提交于 2019-12-13 03:47:48

问题


I am using loops and a counter to put out a numbered list of items. It lists them all at once under 1, and then 2 is another round of listing of all of the items.

The while loop doesn't work and I figured until was better. I also moved counter outside of the first iteriation but that doesn't work either.

require 'pry'
require 'rubygems'
require 'open-uri'
require 'nokogiri'

class KefotoScraper::CLI
  def initialize
    @product_names = []
    @page_url = "https://kefotos.mx/"
  end

  def call
    puts "These are the services that Kefoto offers:"
    list_products
  end

  private

  def home_html
    Nokogiri::HTML(open(@page_url))
  end

  def service_names
    @service_names = home_html.css(".nav-link").map do |link|
      link['href'].to_s.gsub(/.php/, "")
    end

    @service_names.each do |pr|
      @product_names << pr
    end

    @product_names
  end

  def list_products
    i = 1
    n = 0

    until @product_names.length < n do
      @product_names.each {|list_item| puts "#{i} #{list_item}"}
      i += 1
      n += 1
    end
  end

  def service_links
    @service_links ||= home_html.css(".nav-item").map { |link| link['href'] }
  end
end

The list repeats itself over and over again.

[3] pry(#<KefotoScraper::CLI>)> @product_names
=> ["foto-enmarcada", "impresion-fotografica", "photobooks", "impresion-directa-canvas", "impresion-acrilico", "fotoregalos"]
[4] pry(#<KefotoScraper::CLI>)> list_products
1 foto-enmarcada
1 impresion-fotografica
1 photobooks
1 impresion-directa-canvas
1 impresion-acrilico
1 fotoregalos
2 foto-enmarcada
2 impresion-fotografica
2 photobooks
2 impresion-directa-canvas
2 impresion-acrilico
2 fotoregalos

回答1:


def list_products
  @product_names.each_with_index do |list_item, i|
    puts "#{i} #{list_item}"
  end
end

edit: thanks for the feedback, the Tin Man. With your current code, you're looping through @product_names once with until and inside of that you're looping through @product_names with .each. For example if @product_names.length == 3, you'd print 3 * 3 == 9 times!

Since you only need to loop through @product_names once, pick either until or .each. My example above uses .each and here is an example using until:

i = 1
until @product_names.length < i do
  puts "#{i} #{@product_names[i-1]}"
  i += 1
end


来源:https://stackoverflow.com/questions/58421753/how-to-puts-a-number-list-of-items-in-the-array-using-an-until-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!