From: Adam Prescott Date: 2010-10-08T18:20:09+09:00 Subject: Re: named parameters in ruby? > def do_some(v={}) >  a, b, c = v[:a], v[:b], v[:c] > end One thing to remember about this idiom is what happens when you try and default the values: (see http://gist.github.com/616543 for the below code in a prettier format) def foo(hash = { :a => 1, :b => 2 }) a = hash[:a] b = hash[:b] puts a.inspect puts b.inspect end foo #=> # 1 # 2 foo(:a => 10) #=> # 10 # nil So you need something like def foo(hash = {}) hash = { :a => 1, :b => 2 }.merge(hash) a = hash[:a] b = hash[:b] puts a.inspect puts b.inspect end foo #=> # 1 # 2 foo(:a => 10) #=> # 10 # 2 That whole requirement of doing merge is a little messy, I suppose; one reason that proper named/keyword arguments would be nice. Not too much of a problem, though, really. On Thu, Oct 7, 2010 at 9:17 PM, Brian Candler wrote: > xiMera wrote: >> A.new >> a.set_vars( :a => 1. :b =>2 ) >> do_some a > > I think you mean: > >  a = A.new >  a.set_vars ( :a => 1, :b => 2) >  do_some a > > How is this better than > >  do_some :a => 1, :b => 2 > > ? > > Note that if you are using ruby 1.9, then you can also write > >  do_some a: 1, b: 2 > > which (from the caller's point of view) is getting pretty close to named > parameters. > > At the callee's side, multiple assignment keeps things pretty clean: > > def do_some(v={}) >  a, b, c = v[:a], v[:b], v[:c] > end > > Or you can use values_at, which is a bit longer in this case. > >  a, b, c = v.values_at(:a, :b, :c) > > Note that ruby needs to know at *parse* time that a,b and c are local > variables, so it can reserve slots for them in the activation record, > and this assignment achieves that. > > Any solution using eval to create local variables would be very > inefficient, if it could be made to work at all. > > irb(main):010:0> def foo > irb(main):011:1> eval("x = 5") > irb(main):012:1> puts x > irb(main):013:1> end > => nil > irb(main):014:0> foo > NameError: undefined local variable or method `x' for main:Object >  from (irb):12:in `foo' >  from (irb):14 >  from :0 > -- > Posted via http://www.ruby-forum.com/. > >