tags:

views:

40

answers:

4

How to pass range in hash to iterate from index 1 to last?

h = {}

h[1..-1].each_pair do |key,value|
  puts "#{key} = #{value}
end

This code returning error. how may i pass range in hash ??

EDIT:

I want to print first key and value without any calculations.

From second key and value i want to do some calculation on my hash.

For that i have written this code ... store_content_in_hash containing key and values.

first_key_value = store_content_in_hash.shift
f.puts first_key_value[1]
f.puts
store_content_in_hash.each_pair do |key,value|
  store_content_in_hash[key].sort.each {|v| f.puts v }
  f.puts
end

Any better way to solve out this problem ??

+1  A: 

Hashes have no concept of order. There is no such thing as the first or second element in a hash.

So you can't do what you want with hashes.

sepp2k
A: 

Hash is not about the ranges. It's about key value pairs. In ruby 1.8 hash is unordered hence you can't be sure in which order the keys and values will be iterated over which makes "range" thing obsolete. And I believe that you're doing something wrong (tm) in this situation. Can you elaborate on your problem?

On the other note you're getting an error because square brackets in Hash instance accepts keys. So if your hash does not contain 1..-1 as a key - you will get nil value and nil does not respond to each_pair. Try this to get a hold on this:

h = {(1..-1) => {:foo => :bar}}

h[1..-1].each_pair do |key,value| 
  puts "#{key} = #{value}"
end
Eimantas
A: 

As others have pointed out, Hashes are not about order. It's true that 1.9 hashes are ordered, but that's just a convenience, not their primary feature.

If the order is important to you, just use arrays instead of hashes. In your case, an array of pairs (two-element arrays) seems to fit the purpose. And if you need to access it by key, you can always easily convert it to a hash using Hash#[] method.

Mladen Jablanović
+1  A: 

In Ruby 1.9 only:

Given a hash:

h = { :a => :b, :c => :d, :e => :f }

Go Like this:

Hash[Array(h)[1..-1]].each_pair do |key, value|
    # ...
end

This will iterate through the following hash { :c => :d, :e => f } as the first key/value pair is excluded by the range.

banister