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|
?
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 .
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.
In fact, yes! Use parentheses:
h = {:a => 1, :b => 2.2} h.each_with_index do |(k, v), i| p k, v, i end
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With