繁体   English   中英

为什么 Ruby array.each 不迭代数组中的每个项目?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM