Index count method for iterators in ruby? - ruby

When moving over an iteration such as:
array.each do |row|
puts "Current row count: " + row.current_row_index
# do some more stuff
end
Is there a way to get the index of the current iteration / row? Obviously I can just throw in a counter, but I'm curious if there's a shortcut for an index function that shows it's current position.
Been digging through the available methods via pry, however I've not seen anything that seems to do this out of the box.

array.each_with_index |row, index|
puts index
end

If you need exactly the index
array.each_index do |index|
puts index
end

Related

find the index of element being processed in a block, ruby

is there a way to know the index of the array element being processed by a block ?
I am trying to do something like this:
arr.any?{ |element|
# do some processing on the sub array [ element.index + 1 , end]
}
of course I can try and accomplish what I want using a for loop, but I was wondering if I can use blocks to do it, just to have a more ruby-ish code
You can make use of each_with_index and call it without block, so it returns Enumerator:
arr.each_with_index.any? do |el, index|
# your condition using index here
end
You can use
array.each_with_index { |item, index|
puts index
puts item
}

Ruby Put Periodic Progress Messages While Mapping

I am mapping an array of items, but the collection can be quite large. I would like to put a message to console every so often, to give an indication of progress. Is there a way to do that during the mapping process?
This is my map statement:
famgui = family_items.map{|i|i.getGuid}
I have a def that I use for giving an update when I am doing a for each or while loop.
This is the def:
def doneloop(saymyname, i)
if (i%25000 == 0 )
puts "#{i} #{saymyname}"
end
end
I normally put x = 0 before I start the loop, then x +=1 once I am in the loop and then at the end of my loop, I put saymyname = "specific type items gathered at #{Time.now}"
Then I put doneloop(saymyname, x)
I am not sure how to do that when I am mapping, as there is no loop to construct this around. Does anyone have a method to give updates when using map?
Thanks!
You can map with index:
famgui = family_items.with_index.map {|item, index| item.getGuid; doneloop('sth', index)}
Only the last expression is returned from a map, so you can do something like:
famgui = family_items.with_index.map do |i, idx|
if idx % 100 == 0
puts # extra linefeed
# report every 100th round
puts "items left: #{family_items_size - idx}"
STDOUT.flush
end
current_item += 1
print "."
STDOUT.flush
i.getGuid
end
This will print "." for each item and a status report after every 100 items.
If you want, you can use each_with and populate the array yourself like:
famgui = []
family_items.each_with_index do |i, idx|
famgui << i.getGuid
puts "just did: #{idx} of #{family_items.size}"
end

Ruby: loop with index?

Sometimes, I use Ruby's Enumerable#each_with_index instead of Array#each when I want to keep track of the index. Is there a method like Kernel#loop_with_index I could use instead of Kernel#loop?
loop without a block results in an Enumerator, which has a with_index method (and a each_with_index if you prefer that.)
loop.with_index{|_, i| puts i; break if i>100}
You could use Fixnum#upto with Float::INFINITY.
0.upto(Float::INFINITY) do |i|
puts "index: #{i}"
end
But, I'd probably just use Kernel#loop and keep track of the index myself because that seems simpler.
i = 0
loop do
puts "index: #{i}"
i += 1
end
So, yeah, I don't think there's anything like Kernel#loop_with_index.
In recent Ruby versions, Numeric#step has a default limit of Infinity and a step-size of 1.
0.step{|i| puts i ; break if i>100 }

Loop Controller for ".each do |x|" in ERB

I am trying to style the first element output through an object.each do |x| command by applying an .active class. I cannot figure it out though - how would I do that?
Use each_with_index(). Shown below in a non-ERB example for clarity.
['hello', 'world'].each_with_index do |item, index|
if index == 0
puts "This is the first item"
end
puts item
end
Prints out:
This is the first item
hello
world
It seems very obvious:
objects.first.css_options += ' .active'
And then iterate through all objects in usual manner.
In case of variation can be different, for example you want also apply css option to last element:
objects.zip(['active','','',...]).each do |obj,klass|
obj.css_option += klass
...
end
[obj1, obj2].each_with_index do |item, index|
item.css_option += ' .active' if index == 0
end

Syntax for a for loop in ruby

How do I do this type of for loop in Ruby?
for(int i=0; i<array.length; i++) {
}
array.each do |element|
element.do_stuff
end
or
for element in array do
element.do_stuff
end
If you need index, you can use this:
array.each_with_index do |element,index|
element.do_stuff(index)
end
limit = array.length;
for counter in 0..limit
--- make some actions ---
end
the other way to do that is the following
3.times do |n|
puts n;
end
thats will print 0, 1, 2, so could be used like array iterator also
Think that variant better fit to the author's needs
I keep hitting this as a top link for google "ruby for loop", so I wanted to add a solution for loops where the step wasn't simply '1'. For these cases, you can use the 'step' method that exists on Numerics and Date objects. I think this is a close approximation for a 'for' loop.
start = Date.new(2013,06,30)
stop = Date.new(2011,06,30)
# step back in time over two years, one week at a time
start.step(stop, -7).each do |d|
puts d
end
The equivalence would be
for i in (0...array.size)
end
or
(0...array.size).each do |i|
end
or
i = 0
while i < array.size do
array[i]
i = i + 1 # where you may freely set i to any value
end
array.each_index do |i|
...
end
It's not very Rubyish, but it's the best way to do the for loop from question in Ruby
To iterate a loop a fixed number of times, try:
n.times do
#Something to be done n times
end
If you don't need to access your array, (just a simple for loop) you can use upto or each :
Upto:
2.upto(4) {|i| puts i}
2
3
4
Each:
(2..4).each {|i| puts i}
2
3
4
What? From 2010 and nobody mentioned Ruby has a fine for /in loop (it's just nobody uses it):
ar = [1,2,3,4,5,6]
for item in ar
puts item
end
['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}
Ruby's enumeration loop syntax is different:
collection.each do |item|
...
end
This reads as "a call to the 'each' method of the array object instance 'collection' that takes block with 'blockargument' as argument". The block syntax in Ruby is 'do ... end' or '{ ... }' for single line statements.
The block argument '|item|' is optional but if provided, the first argument automatically represents the looped enumerated item.

Resources