首页 > 解决方案 > 为什么 Ruby array.each 不迭代数组中的每个项目?

问题描述

我是 ruby​​ 和 rails 以及一般编码的新手。但我正在开发一个项目,该项目使用 Steam 网络 API 来获取 Steam 用户拥有的游戏列表。我正在尝试获取该信息并将其存储在我自己的表中。我能够将信息输入我的网站,但我只需要选择一部分信息传递到我的表格中。

在我的用户控制器中,我有这个显示:

 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" =>...}]

在我的用户模型中,我定义了这些方法:

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 的对象。

这就是我的问题所在,string_ids.each 到 |app_id| 只经过数组中的第一件事。这是因为我返回的是“这个存在”还是“不存在”?我能做些什么来解决这个问题?

标签: arraysruby-on-railsrubyiteration

解决方案


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      

推荐阅读