Ruby - Picking an element in an array with 50% chance for a[0], 25% chance for a[1]
问题 Nothing too complicated, basically I just want to pick an element from the array as if I were making coin tosses for each index and and choosing the index when I first get a head. Also no heads means I choose the last bin. I came up with the following and was wondering if there was a better/more efficient way of doing this. def coin_toss(size) random_number = rand(2**size) if random_number == 0 return size-1 else return (0..size-1).detect { |n| random_number[n] == 1 } end end 回答1: First guess