Sort a Ruby Hash Array - no implicit Conversion of Symbol into Integer

Asked

Viewed 250 times

0

My question is about sorting a hash within an array in Ruby.

I’m learning to code in Ruby, my first contact with programming, I’m exercising by consuming an api. I managed to get to where I wanted, which was to take the name of the clubs the position and print. My next goal is to sort clubs by position, but using (.Sort) always returns error (no implicit Conversion of Symbol into Integer)

the api I’m consuming is in this https://api.cartolafc.globo.com/clubes which basically returns a hash.

require 'rest-client'
require 'json'

url = 'https://api.cartolafc.globo.com/clubes'

resp = RestClient.get "#{url}"

clubes = JSON.parse(resp.body)

tabela = []
  for chave, valor in clubes 
    nome = valor["nome"]
    posicao = valor["posicao"]

    if posicao != nil
     tabela.push [:clube=>nome, :classificacao=>posicao]

    puts "O nome do time é #{nome} e a posição é #{posicao}º"
    end
  end

res = tabela.sort_by { |item| item[:classificacao] }

puts res

1 answer

0

I made some modifications to the code, turned the table from Array to Hash so it would be better to use Sort. Then just

require 'rest-client'
require 'json'

url = 'https://api.cartolafc.globo.com/clubes'
resp = RestClient.get "#{url}"
clubes = JSON.parse(resp.body)
data = {} # Dados iniciais dos clubes

for chave, valor in clubes
    nome = valor['nome']
    pos = valor['posicao']
    if pos != nil
        data[nome] = nome
        data[nome] = pos
    end
end

data = data.sort{|x, y| x.last <=> y.last} # Usando sort para verificar se o valor x anterior é menor igual ou maior que y anterior e adicionando na hash data já sortido
data.each{|k, v| puts "[#{v}] #{k} Posicao: #{v} "} # Fatiando a hash data deixando tudo bonitinho para imprimir```

Browser other questions tagged

You are not signed in. Login or sign up in order to post.