Is there any way to cause “”, [], and {} to have different behaviors.
I’d like to be able to have {} create OrderedHash’s instead of Hash’s,
but I don’t know how to change this behavior. If I do Hash =
OrderedHash, then Hash.new will create an OrderedHash, but {} still
gives me an old-fashioned hash. If I do
def Hash.new *args
OrderedHash.new *args
end
I get the same results. Is it possible to override these built-in
constructors?
Is there any way to cause “”, , and {} to have different behaviors.
I’d like to be able to have {} create OrderedHash’s instead of Hash’s,
but I don’t know how to change this behavior. If I do Hash =
OrderedHash, then Hash.new will create an OrderedHash, but {} still
gives me an old-fashioned hash. If I do
def Hash.new *args
OrderedHash.new *args
end
I get the same results. Is it possible to override these built-in
constructors?
I thought of something like this three years ago. It’s not possible.
{ x => y } is a Hash no matter what you do.
can be redefined, but only as a method. [1,2,3] will still be a
plain Array.
Is there any way to cause “”, , and {} to have different behaviors.
I’d like to be able to have {} create OrderedHash’s instead of Hash’s,
but I don’t know how to change this behavior. If I do Hash =
OrderedHash, then Hash.new will create an OrderedHash, but {} still
gives me an old-fashioned hash.
This isn’t what you’re looking for, but I think it’s the best answer.
Both Array and Hash have a builtin class method, which can be used to
define new Arrays or Hashes.
a = Array[‘goats’, ‘coats’, ‘asymptotes’]
=> [“goats”, “coats”, “asymptotes”]
h = Hash[‘g’ => ‘goats’, ‘c’ => ‘coats’]
=> {“c”=>“coats”, “g”=>“goats”}
You can use the same class method to get away with really clean
definitions of new Array/Hash derivatives. For example, YAML has an
Omap (ordered hash) class:
Is there any way to cause “”, , and {} to have different behaviors.
I’d like to be able to have {} create OrderedHash’s instead of Hash’s,
but I don’t know how to change this behavior. If I do Hash =
OrderedHash, then Hash.new will create an OrderedHash, but {} still
gives me an old-fashioned hash.
This isn’t what you’re looking for, but I think it’s the best answer.
Both Array and Hash have a builtin class method, which can be used to
define new Arrays or Hashes.
a = Array[‘goats’, ‘coats’, ‘asymptotes’]
=> [“goats”, “coats”, “asymptotes”]
h = Hash[‘g’ => ‘goats’, ‘c’ => ‘coats’]
=> {“c”=>“coats”, “g”=>“goats”}
You can use the same class method to get away with really clean
definitions of new Array/Hash derivatives. For example, YAML has an
Omap (ordered hash) class: