I don't know Ruby, but your issue is that you are taking a^b and then taking the modulus. This may mean you are dealing with giant intermediary numbers. The solution is to use a proper modular exponentiation algorithm. This might be built into Ruby, or you might have to roll your own. Here's some pythonish psuedocode for modular exponentiation by squaring:
def exponent_mod(a, b, mod): r = a while b > 0: if b % 2 == 1: r = (r * r) % mod b = b / 2 a = (a * a) % mod return r
If you're really looking for the highest speed possible, though, this is probably a CPU instruction, if you can find a way to reach that far down the stack.