E
Erik Michaels-Ober
[Note: parts of this message were removed to make it a legal post.]
I've noticed a couple inconsistencies in the way Ruby hashes are treated
(compared to, say, arrays). While I've been able to monkey-patch solutions,
I thought I would bring these inconsistencies to the attention of the group
with they hope that they might be resolved in a future version of the
language, which I love dearly.
For starters, there's no to_hash method on nil. This causes a problem when
I want to call an instance method on an object that may or may not be nil
(for example, a hash of parameters from an HTTP request).
A common way to avoid a NoMethodError is by casting an object to a
particular type before calling a method on it. For example:
string_or_nil.to_s.capitalize
This technique can be used for arrays, floats, integers, and strings. It
would seem to follow that I could do the same for hashes:
hash_or_nil.to_hash.rehash
but instead I must do something like this:
(hash_or_nil || nil).rehash
or patch NilClass like this:
class NilClass
def to_hash
{}
end
end
which seems to me like it shouldn't be necessary for a "primitive" type.
Second, I would argue that there should be + (plus), - (minus), and &
(ampersand) methods on hashes, that function the same way they do for arrays
(concatenation, difference, and intersection, respectively).
These few changes would go a long way toward making Hash a first-class
citizen in Ruby.
I've noticed a couple inconsistencies in the way Ruby hashes are treated
(compared to, say, arrays). While I've been able to monkey-patch solutions,
I thought I would bring these inconsistencies to the attention of the group
with they hope that they might be resolved in a future version of the
language, which I love dearly.
For starters, there's no to_hash method on nil. This causes a problem when
I want to call an instance method on an object that may or may not be nil
(for example, a hash of parameters from an HTTP request).
A common way to avoid a NoMethodError is by casting an object to a
particular type before calling a method on it. For example:
string_or_nil.to_s.capitalize
This technique can be used for arrays, floats, integers, and strings. It
would seem to follow that I could do the same for hashes:
hash_or_nil.to_hash.rehash
but instead I must do something like this:
(hash_or_nil || nil).rehash
or patch NilClass like this:
class NilClass
def to_hash
{}
end
end
which seems to me like it shouldn't be necessary for a "primitive" type.
Second, I would argue that there should be + (plus), - (minus), and &
(ampersand) methods on hashes, that function the same way they do for arrays
(concatenation, difference, and intersection, respectively).
These few changes would go a long way toward making Hash a first-class
citizen in Ruby.