I have a hash in ruby with a complex structure, like this:
something = {}
something[1488343493] = { :type => 'tag', :name => 'v1.2', :sha => 'a66fd116e454378794d24c41c193d385be37436f'}
something[1488288253] = { :type => 'pull', :number => '469', :sha => '190ed76e30a5fa7d357e8bfb78adfa687a673635', :title => "Consistent file uploads "}
something[1468674242] = { :type => 'tag', :name => 'v1.1', :sha => '2cf4549d0181ad1d60fbd3bbe132b599a14a8965'}
something[1488457772] = { :type => 'pull', :number => '476', :sha => '5f51fa23ea79bd9b89703cb93a5e38a0f0a338bb', :title => "Extract i18n strings in modals/* "}
something[1488288044] = { :type => 'pull', :number => '470', :sha => 'ab98ec3bf7cbe04f11a17d30ed07e5323b45d5df', :title => "Stop copy & clickthrough from list summaries "}
This basically contains a list of Github tags and merged pull requests. I can easily sort this with .sort
:
something.sort.each do | key, value | # sorts perfectly fine
p "#{key} #{value[:type]} #{value[:sha]}"
end
But I don't want a sorted hash, but a reversed hash. And I'm totally puzzled I can not reverse it at all, trying to .reverse
it gives NoMethodError
for the hash:
something.reverse.each do | key, value | # undefined method `reverse' for #<Hash:0x0> (NoMethodError)
p "#{key} #{value[:type]} #{value[:sha]}"
end
Trying to reverse_each
does simply nothing:
something.reverse_each do | key, value | # does not reverse at all
p "#{key} #{value[:type]} #{value[:sha]}"
end
Same applies to converting to array and reversing, does nothing at all:
gnihtemos = something.to_a.reverse.to_h # does not reverse at all
gnihtemos.each do | key, value |
p "#{key} #{value[:type]} #{value[:sha]}"
end
gnihtemos = Hash[something.to_a.reverse] # does not reverse at all
gnihtemos.each do | key, value |
p "#{key} #{value[:type]} #{value[:sha]}"
end
I'm running out of options. I'm using Ruby 2.4.0p0
. What else can I do to reverse something
?
reverse
reverses the current order. That means you have to sort first and reverse in a second step:
something.sort.reverse.each { ... }
Or you need to explicitly tell Ruby how to sort:
something.sort_by { |commit_id, _| -commit_id }.each { ... }