Search code examples
ruby-on-railsrubydelete-row

Delete a part of a code with ruby with a variable


I have this code

  def index
    require 'net/http'
    require 'json'

    @url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=100&CMC_PRO_API_KEY=mykey'
    @uri = URI(@url)
    @response = Net::HTTP.get(@uri)
    @coins = JSON.parse(@response)
    @my_coins = ["BTC", "XRP", "ADA", "ETH", "USDT"]
  end

The url brings

{"status"=>{"timestamp"=>"2021-02-16T03:55:40.727Z", "error_code"=>0, "error_message"=>nil, "elapsed"=>21, "credit_count"=>1, "notice"=>nil, "total_count"=>4078}, "data"=>[{"id"=>1, "name"=>"

Using that variable (@coins) how could I give the instruction to delete everythin until ' "data"=>'?


Solution

  •   def index
        require 'net/http'
        require 'json'
    
        @url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=100&CMC_PRO_API_KEY=mykey'
        @uri = URI(@url)
        @response = Net::HTTP.get(@uri)
        @coins = get_coins(@response)
        @my_coins = ["BTC", "XRP", "ADA", "ETH", "USDT"]
      end
    
      def get_coins(response)
        coins = JSON.parse(response)
        coins.slice('data')
      end
    
    

    it will give you only 'data' part. because 'data' is a key of hash same as 'status'

    the @coins variable will remain the same, but the output is a new variable which is result from slice operation

    you can also delete using delete operation then @coins will change to remaining key

    @coins.delete('status')
    puts @coins #{"data"=>[{"id"=>1, "name"=>"somename"}]
    
      def index
        require 'net/http'
        require 'json'
    
        @url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=100&CMC_PRO_API_KEY=mykey'
        @uri = URI(@url)
        @response = Net::HTTP.get(@uri)
        @coins = JSON.parse(response)
        @coins.delete('status')
        @my_coins = ["BTC", "XRP", "ADA", "ETH", "USDT"]
      end