Skip to main content
1 of 2
poc
  • 605
  • 4
  • 7

How to make the end of loop more readable in Ruby

There are some blocks in my code.

To make it easier to read, I often append comment after the end

such as

  end # end upto
  end # fileopen

Because sometimes the indentation still not easy for read.

Is there any better practice?

And my indentation is 2 spaces, is it OK for most Rubier ?

require "faker"
real_sn = 2124100000
File.open("lib/tasks/tw_books.txt", "r").each do |line|
  # author = Faker::Lorem.words(2..5).join(' ').gsub('-','').gsub('\s+','\s')

  1.upto(1000).each do |x|

    location = Faker::Lorem.words(5)
    book_name, author, publisher, isbn, comment = line.strip.split("|||")
    ap(line)
    isbn = isbn[/\d+/]
    real_sn+=1
    bk = Book.new(:sn => real_sn,:name => book_name, :isbn=>isbn,
                  :price =>Random.rand(200..5000), :location=>location, :category=>["商業","歷史","體育","政治"].sample,
                  :author => author, :sale_type => [:fix_priced, :normal, :promotion].sample, :publisher => publisher,
                  :release_date => rand(10.years).ago, :comment => comment
                  )
    if bk.save()
      if (real_sn%100)==0
        puts book_name
      end
      Sunspot.commit
    else
      puts real_sn
      puts bk.errors.full_messages
    end
  end # end upto
end # fileopen
poc
  • 605
  • 4
  • 7