Sorting crawled information?

2019-09-16 02:35发布

问题:

Here is the result of the page I successfully crawled:

The problem is that I've only been given numbers! There is no separation. My goal is to separate and sort them.

Each of these numbers means something. But let's take the first three. 5553 is the player's rank, 2591 is the player's level, and 1287238956 is the player's experience points.

How do I display this information in a format like this (like a table)?

Skill    Rank    Level    Experience

Overall  5553    2591     1287238956

Here is my PagesController:

class PagesController < ApplicationController
  def home
    require 'open-uri'
    @username = "brink"
    @url = "http://hiscore.runescape.com/index_lite.ws?player=#{@username}"
    @doc = Nokogiri::HTML(open(@url))
  end

  def help
  end
end

Here is my home view:

<h1>Welcome to xpTrack</h1>

<%= @doc.text %>

What are my options?

What I have tried and what I am doing

  1. I have looked into the split method, but that apparently only works for arrays?
  2. I have also noticed that there is a space between every separation point I need to make. Guess now it's just a matter of being able to call upon one of those units.
  3. Currently trying to convert @doc into a string and somehow break it apart by spaces.
  4. ^^^ Well that sure didn't work.

回答1:

Enumerable#each_slice this help you for build table. In you case
data from another answer

=> data = "5553,2591,1287238956 5553,2591,1287238956 5553,2591,1287238956 5553,2591,1287238956"

=> data.split(' ').each_slice(3) { |a| puts a }
=> 5553,2591,1287238956
   5553,2591,1287238956
   5553,2591,1287238956
   5553,2591,1287238956


回答2:

If you have a bunch of data, don't upload a screenshot...

Given some example-data:

data = "5553,2591,1287238956 5553,2591,1287238956 5553,2591,1287238956 5553,2591,1287238956"

You can create an interims class for the data like

Player = Struct.new(:rank, :level, :experience)

And create a list of those players for access in your view

@players = data.split(' ').map { |data| Player.new(*data.split(',')) }