How to re-replace Hash default value behaviour?

S

Siep Korteling

Hash.new(0) and the block form of Hash.new{_smart_stuff_} come in
really handy while reading in a hash.
When the reading is done however, my hash serves to provide data. At
that stage, the default_value behaviour gets in the way. For instance,
if the hash contains the number of goals for soccerplayers, I don't want
the hash to return value "0" for the key "Wolfgang Amadeus Mozart"; by
then I want plain old Nil, or "No data available".

failed experiment:

Class Hash
def default_proc
Nil
end
end

How can Hash.new behaviour be changed?

regards,
Siep
 
M

matt neuburg

Siep Korteling said:
Hash.new(0) and the block form of Hash.new{_smart_stuff_} come in
really handy while reading in a hash.
When the reading is done however, my hash serves to provide data. At
that stage, the default_value behaviour gets in the way. For instance,
if the hash contains the number of goals for soccerplayers, I don't want
the hash to return value "0" for the key "Wolfgang Amadeus Mozart"; by
then I want plain old Nil, or "No data available".

failed experiment:

Class Hash
def default_proc
Nil
end
end

How can Hash.new behaviour be changed?

regards,
Siep

h = Hash.new.merge(h)

So for example:

h = Hash.new(0)
h[:a] += 2
h[:a] += 1
h[:b] += 4
p h #=> {:a=>3, :b=>4}

h = Hash.new.merge(h)
p h[:c] #=> nil, it's now returning plain old nil

m.
 
A

Andrea Fazzi

Siep said:
Hash.new(0) and the block form of Hash.new{_smart_stuff_} come in
really handy while reading in a hash.
When the reading is done however, my hash serves to provide data. At
that stage, the default_value behaviour gets in the way. For instance,
if the hash contains the number of goals for soccerplayers, I don't want
the hash to return value "0" for the key "Wolfgang Amadeus Mozart"; by
then I want plain old Nil, or "No data available".

failed experiment:

Class Hash
def default_proc
Nil
end
end

How can Hash.new behaviour be changed?

regards,
Siep

a = Hash.new(0)

# do something with a

a = Hash.new { |h,k| h[k] = "No data available" }.merge(a)

But I don't know if this is what you want.

Bye.
Andrea
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top