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.
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:
foo # use default here
foo.set_new_default 'bla'
foo # now we will use the new default 'bla' here.
Is there ANY way to achieve the above?
Obviously, for foo. to work, it would have to
return an object or module on which to call
set_new_default()
I am not sure that this is possible though.
For any helpful pointers, I am thankful.
···
--
Posted via http://www.ruby-forum.com/.