简体   繁体   中英

Why is Ruby array.each do not iterating over each item in array?

I'm new to ruby and rails and coding in general. 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. 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.

In my users controller I have this for show:

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

In my users model I define these methods:

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,..]

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.

This is where the problem is for me, the string_ids.each to |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      

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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