【发布时间】:2020-05-06 22:42:59
【问题描述】:
所以,我正在尝试初始化多个对象并将它们添加到列表中。我想要发生的是通过运行Market.new,我希望将 api 中的每个项目都添加为对象。下面是我认为可能有效的代码。但是,它将相同的对象添加到列表中 100x。有没有办法做到这一点?
def initialize
data = JSON.parse(open(BASE_URL + "markets?vs_currency=usd").read)
i = 0
# looping until we hit the end of the list. adding them all as objects.
while i < data.length
@id = data[i]["id"].to_s
@name = data[i]["name"].to_s
@symbol = data[i]["symbol"].to_s
@price = data[i]["current_price"].to_s
@price_movement_24h = data[i]["price_change_percentage_24h"].to_s
@market_cap = data[i]["market_cap"].to_s
@@market << self
i += 1
end
end
这给了我添加到 @@market 列表 100 倍的相同对象。
=> [#<Market:0x0000561b3f853f30
@id="iostoken",
@market_cap="43969067",
@name="IOST",
@price="0.0036523",
@price_movement_24h="-0.76702",
@symbol="iost">,
#<Market:0x0000561b3f853f30
@id="iostoken",
@market_cap="43969067",
@name="IOST",
@price="0.0036523",
@price_movement_24h="-0.76702",
@symbol="iost">,
【问题讨论】: