删除带有变量 ruby 的代码的一部分

Delete a part of a code with ruby with a variable

我有这个代码

  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

url带来

{"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"=>"

使用那个变量 (@coins) 我怎么能给出删除所有内容的指令直到“数据”=>'?

  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

它只会给你 'data' 部分。因为 'data' 是散列的键,与 'status'

相同

@coins 变量将保持不变,但输出是切片操作产生的新变量

您也可以使用删除操作删除@coins 将更改为剩余密钥

@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