开发者

A More elegant way of doing this?

I keep saying to myself there must be a better way but I can't see it right now.. ideas?

i = 0; lose = 0; win = 0
while i < @array.size
  results = @array[i].results
  q = 0
  while q < results.size
    if results[q].to_i == 0 then
      lose += 1
    elsif results[q].to开发者_开发知识库_i == 1 then
      win += 1
    else
      puts results[q]
      puts "false"
    end
    q += 1
  end
  i+=1
end
if win == lose then
  puts "true"
else
  puts "false"
end


You can use array.each instead of while loops.

You can use array.count instead of manually inspecting each array:

lose = results.count { |r| r.to_i == 0 }
win = results.count { |r| r.to_i == 1 }

# or possibly if the array can only contain wins and losses
win = results.count - lose


f = @array.flatten
puts (f.count('0') == f.count('1'))
puts f-%w{0 1}


Provided you only have 0 and 1 in your arrays, you could in theory simply add up the values of all .to_i entries, then check if this value is exactly half of the total number of entries in your arrays. Its hard to say if there's a better way of doing this without knowing more information. Are win and lose counts used anywhere afterwards? Is this a function that returns right away or is this embedded in a larger function? Are all your results array exactly the same size? Cheers and happy coding!


Splitting an array in two parts according to some test can be done using Enumerable#partition:

win, lose = results.partition {|r| r.to_i == 1}.map(&:size)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜