mardi 23 décembre 2014

Ruby: How to get the default value of optional proc arguments

Let's say I have a proc/lambda/block/method/etc like so:



2.1.2 :075 > procedure = Proc.new { |a, b=2, *c, &d| 42 }
=> #<Proc:0x000000031fcd10@(irb):75>


I know I can find out the names of the parameters with:



2.1.2 :080 > procedure.parameters
=> [[:opt, :a], [:opt, :b], [:rest, :c], [:block, :d]]


But how do I go about getting the value that a given optional parameter would assume if it is not given?




PS: Yes. I know this has been asked/answered before here, but the previous solution requires the use of the merb gem, which is actually slightly misleading. merb itself depended on the methopara gem (unless you're on JRuby or MRI, which I am not) which itself provided the feature at the time the question was answered.


Sadly, presently, methopara appears to be abandonware. Also, it only ever supported ruby 1.9 (and not even the latest version thereof), so I'm looking for a solution that works for current ruby versions.






Aucun commentaire:

Enregistrer un commentaire