Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, is there a way to use something like hash.each_with_index do |[k,v], i|?

Tags:

ruby

Otherwise, it needs to be

h = {:a => 1, :b => 2.2} h.each_with_index do |pair, i|   k = pair[0]; v = pair[1]   p k, v, i end 

and setting the k and v this way seems a bit clumsy. Can it be simpler or something like

h.each_with_index do |[k,v], i| 

?

like image 470
nonopolarity Avatar asked May 24 '11 22:05

nonopolarity


People also ask

How do you check if something is a hash in Ruby?

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .

Do hashes have indexes Ruby?

A Hash is a collection of key-value pairs. It is similar to an Array , except that indexing is done via arbitrary keys of any object type, not an integer index.


2 Answers

In fact, yes! Use parentheses:

h = {:a => 1, :b => 2.2} h.each_with_index do |(k, v), i|   p k, v, i end 
like image 153
molf Avatar answered Oct 08 '22 08:10

molf


The Inject call should get what you want, http://www.ruby-doc.org/core/classes/Enumerable.src/M001494.html check that and scroll to the Inject portion, should work like a charm!

like image 41
Jake Kalstad Avatar answered Oct 08 '22 10:10

Jake Kalstad