Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate hash for specific range

Tags:

ruby

hash

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 ??

like image 317
krunal shah Avatar asked Dec 29 '22 07:12

krunal shah


2 Answers

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.

like image 186
horseyguy Avatar answered Jan 11 '23 08:01

horseyguy


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.

like image 42
sepp2k Avatar answered Jan 11 '23 08:01

sepp2k