define_method(:initialize){|value=nil| @value = value if value}
which doesn't seem to be possible because of the "value=nil" part. Is
there some way to do this that isn't eval? Eval would work fine since
this is pretty static code and I have unit tests for it but I try to
avoid it if I can. I've only used it before for performance to turn
some code with runtime tests into eval-time tests.
define_method(:initialize){|value=nil| @value = value if value}
First of all, you don't need the `if value' part -- when Ruby sees @value, it is immediately created, with the value nil, so there's no problem with giving it the value nil explicitly. Second, I believe you can just do this:
At Tue, 25 Jul 2006 19:33:38 +0900,
=?ISO-8859-1?Q?Pedro_C=F4rte-Real?= wrote in [ruby-talk:203711]:
define_method(:initialize){|value=nil| @value = value if value}
define_method(:initialize) {|*values|
case values.size
when 0
value = nil
when 1
value = values.first
else
raise ArgumentError, "wrong number of arguments (#{values.size} for 0)"
end @value = value
}
First of all, you don't need the `if value' part -- when Ruby sees @value, it is immediately created, with the value nil, so there's no
problem with giving it the value nil explicitly.
Yes, I knew that.
Second, I believe you
can just do this:
define_method(:initialize){|value| @value = value}
If #initialize is called with no arguments, `value' will just be nil,
although IRB may issue a warning.
That's what I have but it throws a warning and I wanted to shut it up.
Guess I'll have to do the eval.
Thanks,
Pedro.
···
On 7/25/06, Daniel Schierbeck <daniel.schierbeck@gmail.com> wrote:
define_method(:initialize) do |*values|
case values.size
when 0..1 @value = values.first
else
raise ArgumentError, "wrong number of arguments (#{values.size} for
0)"
end
end
or perhaps
define_method(:initialize) do |*values| @value = values.shift
unless @value.length == 0
raise ArgumentError, "wrong number of arguments (#{values.size} for
0)"
end
end
Yep, this works great, thanks. It's an eval but it's the one with a
block instead of a string. Didn't know "def" worked inside a block.
Must free myself of silly mental restrictions brought over from lesser
languages...
Thanks,
Pedro.
···
On 7/25/06, Dr Nic <drnicwilliams@gmail.com> wrote:
define_method(:initialize) do |*values| @value = values.shift
unless @value.length == 0
raise ArgumentError, "wrong number of arguments (#{values.size} for
0)"
end
end
define_method(:initialize) do |*values|
raise ArgumentError, "wrong number of arguments (#{values.size} for 0)" if values.length > 1 @value = values.first
end