[英]Why is Ruby array.each do not iterating over each item in array?
我是 ruby 和一般的導軌和編碼的新手。 但我正在開發一個項目,該項目使用蒸汽 web api 來獲取蒸汽用戶擁有的游戲列表。 我正在嘗試獲取該信息並將其存儲在我自己的表中。 我能夠將信息輸入我的站點,但我需要 select 僅將一部分信息傳遞到我的表中。
在我的用戶 controller 我有這個展示:
def show
#renders the user page
@user = User.find(params[:id])
@player = SteamWebApi::Player.new(@user.steam_id)
end
在用戶顯示視圖中,我有這個:
<% user_class = User.new %>
<h2> These are the games you own </h2>
<% @games = @player.owned_games %>
<% @steam_game_ids = user_class.get_steam_id_from_games(@games) %>
<br>
<%= user_class.check_if_games_exit_in_table(@steam_game_ids) %>
@player.owned_games給出了這樣的游戲數組: [{"appid" => 1234}, "something" => 23123}, {"appid" =>...}]
在我的用戶 model 我定義了這些方法:
def get_steam_id_from_games(games)
games.games.map{|x| x.values[0]}
end
def check_if_games_exist_in_table(steam_ids)
string_ids = steam_ids.map(&:to_s) #not converting to string
string_ids.each do |app_id|
if Game.exists?(game_app_id: app_id)
return "this exists"
else
return "#{app_id} doesn't exist"
end
end
end
get_steam_id_from_games為每個游戲創建一個僅包含 appid 值的數組:[1234, 234545,..]
check_if_games_exist_in_table應該采用 appid 數組,將項目轉換為字符串(這就是我在表中存儲信息的方式),然后檢查表中是否存在具有相同 appid 的 object。
這就是我的問題所在, string_ids.each 到 |app_id| 只經過數組中的第一件事。 這是因為我返回的是“這個存在”還是“不存在”? 我能做些什么來解決這個問題?
def check_if_games_exist_in_table(steam_ids)
string_ids = steam_ids.map(&:to_s) #not converting to string
array_of_non_existing_ids = []
string_ids.each do |app_id|
if !Game.exists?(game_app_id: app_id)
array_of_non_existing_ids.push app_id
end
end
return "#{array_of_non_existing_ids.join(',')} doesn't exist" if array_of_non_existing_ids.any?
return "this exists"
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.