Iterate a hash for a specific range

How to pass a range to a hash to iterate from index 1 to the last?

h = {}

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

This code returns an error. how can i go through the range in a hash ??

EDIT:

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

From the second key and value, I want to do some calculations on my hash.

For this, I wrote this code ... store_content_in_hash containing the 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 this problem?

+3
source share
4 answers

Only in Ruby 1.9:

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 move through the next hash { :c => :d, :e => f }, since the first key / value pair is excluded by the range.

+7
source

. , .

, , , .

+2

. . 1.8 , , , - "" . , - (tm) . ?

, , Hash . , 1..-1 , , nil each_pair. , :

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

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

, . , 1,9 , , .

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

0
source

Source: https://habr.com/ru/post/1767216/


All Articles