[英]Why is Ruby array.each do not iterating over each item in array?
I'm new to ruby and rails and coding in general.我是 ruby 和一般的导轨和编码的新手。 But I'm working on a project that uses the steam web api to get a list of games owned by a user on steam.
但我正在开发一个项目,该项目使用蒸汽 web api 来获取蒸汽用户拥有的游戏列表。 I'm trying to take that information and store it in my own table.
我正在尝试获取该信息并将其存储在我自己的表中。 I was able to get the information into my site but I need to select only one part of the information to pass into my table.
我能够将信息输入我的站点,但我需要 select 仅将一部分信息传递到我的表中。
In my users controller I have this for show:在我的用户 controller 我有这个展示:
def show
#renders the user page
@user = User.find(params[:id])
@player = SteamWebApi::Player.new(@user.steam_id)
end
In the users show view I have this:在用户显示视图中,我有这个:
<% 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) %>
The @player.owned_games gives an array of games like this: [{"appid" => 1234}, "something" => 23123}, {"appid" =>...}] @player.owned_games给出了这样的游戏数组: [{"appid" => 1234}, "something" => 23123}, {"appid" =>...}]
In my users model I define these methods:在我的用户 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 makes an array with only the appid values for each game:[1234, 234545,..] get_steam_id_from_games为每个游戏创建一个仅包含 appid 值的数组:[1234, 234545,..]
check_if_games_exist_in_table is supposed to take the appid array, converts the items to strings (that's how I store the information in my table), and then checks if there is an object in the table with the same appid. check_if_games_exist_in_table应该采用 appid 数组,将项目转换为字符串(这就是我在表中存储信息的方式),然后检查表中是否存在具有相同 appid 的 object。
This is where the problem is for me, the string_ids.each to |app_id|这就是我的问题所在, string_ids.each 到 |app_id| only goes through the first thing in the array.
只经过数组中的第一件事。 Is this because I'm returning "this exists" or "doesn't exist"?
这是因为我返回的是“这个存在”还是“不存在”? What can I do to fix this problem?
我能做些什么来解决这个问题?
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.