What order are method arguments evaluated in Ruby?

Viewed 1118

Up until my attempt to answer this question I had always assumed arguments were evaluated from left to right the way we type them. For example we have some method:

def foo(a,b,c)

Is there a way to monitor variable definitions and values in a Ruby program as time passes? If you call foo 0,1,2 how can you prove that variables assigned in the following order?

time 0: a = 0

time 1: b = 1

time 2: c = 2

I realize my example is trivial because I have the same type of argument for a, b, c but it potentially gets muddied up when you introduce default arguments, keyword arguments, and array arguments. If no one knows the answer I would appreciate suggestions on how to determine the answer.

Basically the Ruby equivalent of this.

4 Answers

For anybody coming here looking for argument assignment order (what the question asks at the time of my post) and not parameter assignment order. I always assumed they were evaluated in the order written until I tried writing some odd code and got a strange result. steenslag gave me an idea of how I could test it:

def arg_test(a, b)
  puts([a, b].inspect '- out of order!') if a > b
end

1000000.times {
  arg_test(Time.now, Time.now)
}

This results in no output. So it seems they are assigned in order and my other code probably just has a bug.

Related