Hello.
Situation is this:
I have a method call foo.
Calling this method works.
It can accept zero, up to an unlimited amount of arguments.
Examples:
foo
foo ‘hi’
foo ‘hi’,‘there’
So far, so good.
Now, to make this a little bit more complicated,
the first call to foo in this example, will invoke
the default argument. Example:
def foo(i = ‘default value here’, *other_arguments)
puts i
end
Now the thing is, I want to change the default value
to that method.
My first idea was to use a constant.
DEFAULT_ARGUMENT = ‘default value here’
And then:
def foo(i = DEFAULT_ARGUMENT)
end
But I also want to change the default argument, and
ruby annoys me when I do so, because it is a constant.
(Sidenote - ruby should either enforce that a constant
is a constant, or it should not warn about it. The
current solution is a middle-way, which I don’t
think is good.)
So my idea was to use an array as constant, because
ruby does not warn you if the content of an array
constant is changed.
DEFAULT_ARGUMENT = [‘default value here’]
And then:
def foo(i = DEFAULT_ARGUMENT[0])
I then came up with a slightly better
solution. I will wrap this into a module, like
so:
module Foo
DEFAULT_ARGUMENT = [‘default value here’]
def self.to_s
return DEFAULT_ARGUMENT[0]
end
def self.set_new_default(i)
DEFAULT_ARGUMENT[0] = i
end
end
def foo(i = Foo.to_s)
end
This works nicely. If anyone has a cleaner or
better solution, I am all ears.
But one thing is missing still, because I want
to be able to “work on a method object” directly,
without much syntax sugar.
Specifically, I want to do this here:
foo # use the first, initial default here
foo.set_new_default ‘bla’ # change to a new, different default here
foo # now we will use the new default ‘bla’ here.
Is there ANY way to achieve the above? Especially
with the syntax that I want to showed there.
The real code has several foo-like methods, and
I would like to change the default values that
these methods have, in exactly that unified way,
via .set_new_default()
Obviously, for any “foo.” call to work, it would have
to return an object or module on which to actually call
set_new_default()
I am not sure that this is possible though. Is this even
possible in Ruby? And if it is not possible, why is this
not possible?
For any helpful pointers, I am thankful.