Ryan Hall
Ryan Hall

Reputation: 23

Using Ruby: Why is my array printing the results then an array of with idex numbers

I have two methods:

pwsplayerindex finds a person that is in an array multiple times and gives the index of where their name is.

statarray uses the index # from pwsplayerindex to find other data in an array with hashes.

def pwsplayerindex(inplayer)
arr = Array.new
pwsarr.each_with_index do |val,index|
if val['player'] == inplayer then arr << index end
end
    arr
end

def statarray(index,stat)
indexarr = Array.new 
pwsplayerindex((pwsarr[index]['player'])).each { |x| puts (pwsarr[x][stat])}   
end  

 print statarray(0,'play')

Why does the result yield:

51.0
29.9
29.4
28.1
24.6
16.6
[0,82,88,113,192,472]

All I want it to give me is:

51.0
29.9
29.4
28.1
24.6
16.6

Upvotes: 2

Views: 53

Answers (2)

Ryan Hall
Ryan Hall

Reputation: 23

This is what I was shooting for:

def pwsplayerindex(inplayer)
arr = []

  pwsarr.each_with_index do |val,index|
    if val['player'] == inplayer then arr << index end
  end
  arr
end

def statarray(i,stat)
indexarr = Array.new

  pwsplayerindex((pwsarr[i]['player'])).each do |x|
    indexarr << pwsarr[x][stat]
  end
    indexarr
end 

puts statarray(0,'play')

This gives me what I was aiming for in my original question. It was a simple fix. I didn't realize I was printing in the method.

Upvotes: 0

Ursus
Ursus

Reputation: 30056

puts statarray(0,'play')

should be just

statarray(0,'play')

otherwise you print the return value of the function, which is the entire array (because the each method)

Upvotes: 2

Related Questions