Kelso
Kelso

Reputation: 387

Count from list in ruby

Im thinking this is correct, but probably WAY off.

I have a string formatted as such name, name1, name2, name3, name4, etc

admins_count = 0
if ["name2", "name3"].include?(player_list)
  admins_count += 1
end

Is this the proper way to count matches in a list?

Essentially, its a list of players, I want to count how many of the names in the second list mtch against player_list.

this is what worked for me a combo of things

player_list = response[3].split(" ", 2)[1].chomp[1..-2]
admin_list = "Howard_Roark, Gerrit8500, fffizzz"
mod_list = "ZionRx, rodtang, fuzzamuzza, DJRedFlames, bingbong2715, ErebusAnima, Twentytenor2, zephyrnug, Tiberione, deadkill02, tTheoRyy, PyneApll, tercept, Hestehaven, Orjis87, Yaltar101"

mod_arr = mod_list.split(", ")
admin_arr = admin_list.split(", ")
player_arr = player_list.split(", ")

mods_count = 0
mod_arr.each do |s|
        mods_count += 1 if player_arr.include? s
end

admins_count = 0
admin_arr.each do |s1|
        admins_count += 1 if player_arr.include? s1
end

puts "players.value #{player_count}"
puts "mods.value #{mods_count}"
puts "admins.value #{admins_count}"

Upvotes: 0

Views: 284

Answers (2)

Charles Caldwell
Charles Caldwell

Reputation: 17169

If player_list is an Array, you could use the & operator. It takes two Arrays and returns a new Array of only the items the two Arrays have in common (with no duplicates).

# I'm assuming player_list becomes a string of 'name1, name2, name3...' after 
# the 'chomp' method
player_list = response[3].split(" ", 2)[1].chomp[1..-2].split(",").map(&:strip)
admins_count = (["name2", "name3"] & player_list).size

So, if player_list contains "name2" then it will return ["name2"]. We then call .size on that and we would get 1 which would get assigned to admins_count.

Upvotes: 1

Hunter McMillen
Hunter McMillen

Reputation: 61512

I think this is more of what you want:

formatted_string = "name,name1,name2,name3,name4";
string_arr = formatted_string.split(",")

string_arr.each do |s|
   admin_count += 1 if player_list.include? s
end

Upvotes: 1

Related Questions