New Alexandria
New Alexandria

Reputation: 7324

How does Ruby allow method param defaults to be derived from earlier params?

In Ruby, params passed first in the list can be the used to define defaults for later params.

class Buddy
  def test opts, spec = opts[:red]
    puts spec
  end
end


n = Buddy.new
n.test( {:red => 3} )

What wizardry does this?
Are all params loaded serially? Is this behaviour only for proc, but not lambda?

Upvotes: 2

Views: 82

Answers (1)

7stud
7stud

Reputation: 48599

Method calls cause the arguments to be assigned to the parameter variables:

    do_stuff(10, 20)  #method call
def do_stuff( x, y )  #method definition

resulting assignments: x = 10, y = 20

Parameter variables are local variables. After a value gets assigned to a local variable, the local variable can be accessed. Parameter variable assignment doesn't seem to work any differently than writing:

x = {a: 1, b: 2}
y = x[:a]

puts x, y

--output:--
{:a=>1, :b=>2}
1

Is this behaviour only for proc

Where is there a proc in your example? In any case,

func = Proc.new do |x, y=x[:a]| 
  puts x, y  
end

func.call({a: 1, b: 2})

--output:--
{:a=>1, :b=>2}
1

lambdas:

func = lambda do |x, y=x[:a]| 
  puts x, y  
end

func.call({a: 1, b: 2})

--output:--
{:a=>1, :b=>2}
1

So parameter variable assignment works the same way for methods, procs, and lambdas.

Upvotes: 1

Related Questions