0

I have a method that looks like this:

class A
  def my_method(a: 'key value', b = 'opt value')
    # ...
  end
end

Using reflection, I can get the parameter names like this:

A.new.method(:my_method).parameters
# => [[:key, :a], [:opt, :b]]

How can I get the default values of these parameters without invoking my_method?

sawa
  • 165,429
  • 45
  • 277
  • 381
Max
  • 15,157
  • 17
  • 82
  • 127
  • It looks like this can be done using a Merb's action-args library. Take a look at this answer and see if it gets you what you want? As Antti suggests, I would cherry pick what you want from Merb's source code. http://stackoverflow.com/a/625222/227397 – Jeff Price Sep 03 '15 at 14:02
  • Just a nitpick but I think optional params need to go first in the argument list, so `my_method(b = 'opt', a: 'key')` – Anthony Sep 03 '15 at 14:21
  • 1
    Why do you want to do that? What do you try to achieve? – spickermann Sep 03 '15 at 14:21
  • @spickermann I'm trying to get the default values. – Max Sep 03 '15 at 14:44
  • @Max : Sure, but why do you need the default values? What do you want to do with this information? This approach seems to violate the [Law of Demeter](https://en.wikipedia.org/wiki/Law_of_Demeter). And qour question sounds like a [xy problem](http://meta.stackexchange.com/a/66378/284887) to me. – spickermann Sep 03 '15 at 15:32
  • I'm just playing around with Ruby and I'm curious how one would accomplish this. I have no greater problem to solve :) – Max Sep 03 '15 at 15:37

1 Answers1

2

This is not possible. I can't find the thread right now, but matz has explicitly said that this is by design. The problem is that the default value is an arbitrary expression, and since everything in Ruby is an expression, it can be anything.

For example, what about this:

def foo(bar = if rand < 0.5 then Time.now else rand end)

What would your proposed method return here?

Basically, you have two choices:

  • Evaluate the default value expression. This means you will get some value, but that doesn't tell you much about what the real expression is.
  • Don't evaluate the default value expression, by packaging it up in a Proc. But there's no way to get the expression out of a Proc again.

So, either way, you don't actually get any useful information.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653