Hash#shift

H

Harry Kakueki

Hi,

I was reading this http://www.rubycentral.com/book/ref_c_hash.html#Hash.shift

and I wondered how this could be useful. I must be missing something.

I tried this

ahash = {"a" => "apple","b"=> "boat","c" =>"car", "dog" => "zebra",
"elephant" => "yak"}
p ahash #=>{"a" => "apple","b"=> "boat","c" =>"car","elephant" =>
"yak", "dog" => "zebra"}
p ahash.shift #=>["a", "apple"]
p ahash.shift #=>["b", "boat"]
p ahash.shift #=>["c", "car"]
p ahash.shift #=>["elephant", "yak"]
p ahash.shift #=>["dog", "zebra"]

Since the order of a hash is not guaranteed, you do not know what you
are shifting at any given time. Is this right?
If you just wanted to shift everything you could use Hash#each.

What am I missing?

Harry
 
R

Robert Klemme

Hi,

I was reading this
http://www.rubycentral.com/book/ref_c_hash.html#Hash.shift

and I wondered how this could be useful. I must be missing something.

I tried this

ahash = {"a" => "apple","b"=> "boat","c" =>"car", "dog" => "zebra",
"elephant" => "yak"}
p ahash #=>{"a" => "apple","b"=> "boat","c" =>"car","elephant" =>
"yak", "dog" => "zebra"}
p ahash.shift #=>["a", "apple"]
p ahash.shift #=>["b", "boat"]
p ahash.shift #=>["c", "car"]
p ahash.shift #=>["elephant", "yak"]
p ahash.shift #=>["dog", "zebra"]

Since the order of a hash is not guaranteed, you do not know what you
are shifting at any given time. Is this right?
If you just wanted to shift everything you could use Hash#each.

What am I missing?

I never had use for this myself but it might be useful in cases where
you want to iterate through a (possibly temporary) Hash and make sure
that elements that you have processed are removed. Like
processing: baz - 3
processing: foo - 1
processing: bar - 2
=> nil=> {}

If you now leave the loop early (for whatever reasons, "return" or
raise) you only leave elements that still have to be processed in the Hash.

Kind regards

robert
 
H

Harry Kakueki

I never had use for this myself but it might be useful in cases where
you want to iterate through a (possibly temporary) Hash and make sure
that elements that you have processed are removed. Like

processing: baz - 3
processing: foo - 1
processing: bar - 2
=> nil
=> {}

If you now leave the loop early (for whatever reasons, "return" or
raise) you only leave elements that still have to be processed in the Hash.

Kind regards

robert

OK.
You would be shifting in a somewhat random order but you would be able
to keep track of what had not yet been shifted.

Thanks for that example.

Harry
 

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
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top