My first Ruby language idea is simple. Instead of having every method take a default value, do the following:
class Object
def default(*args)
self
end
end
class NilClass
def default(arg)
arg # And have a block form, too.
end
end
How this would work:
Currently, the following would default to "i" if the element doesn't exist.
[4, 6, 9].fetch(4, "i")
This would do the same thing:
[4, 6, 9][4].default("i") or [4, 6, 9].fetch(4).default("i")
It would reduce a lot of repeated code in the actual Ruby codebase and would give more room for parameters to functions (because we don't really have named parameters).
Plus, the Ruby Way is not to do:
retVal = defaultValue if retVal.nil?
And this would solve that.
···
-------
My second idea is a lot more out there but, I feel, still a good idea.
A form of all the classes with Enumerable mixed in (hash, array, etc) where all the methods like select return not the values that were selected but an object that contains a reference back to the index of the array where it was stored.
This would allow things like:
ary = [4, nil, 6, nil]
ary.select{|x| x.nil?}[1].set(2)
ary # => [4, nil, 6, 2]
As it is now, the above wouldn't work because select returns an array of values from the array, so calling set only changes the value in the array that was created by set.
With my idea, select would return an "ArrayValue" (or something) class, and the set parameter of that class would update the original array.
The ArrayValue class could be implemented as such:
class ArrayValue
def initialize(origArray, origIndex)
@origArray, @origIndex = origArray, origIndex
end
def get
@origArray[@origIndex]
end
def set(newObj)
@origArray[@origIndex] = newObj
end
# more methods, like delete, etc could be implemented.
end
There are some problems to this right now, mainly:
-Have to use a method to set, not the un-overloadable = lanugage construct.
-Need some disambiguation between methods that return values and methods that return ArrayValues (maybe everything returns an ArrayValue and one must use ArrayValue#get).
-Fundamental Redesign
Despite these problems, I see a lot of use cases for ArrayValue.
Thanks for reading (that long thing),
Dan