Ruby way to take some action only once in a loop?


#1

This example is slightly contrived, but I hope it does illustrate the
question.

Say you’re generating table from an array and want to output header row
only if there will be actual rows in the table.

Basically I would like something like this:

rows = [“row1”, “row2”]

rows.each do |row|
do_once do
write(header) # this block gets executed only once for whole loop
end

write(row)
end

I know, it’s very questionable from the “best practices” point of view
as it breaks execution sequence, but it would be interesting to see
possible solutions.

Here is dumb one which relies on Proc#binding for keeping flags about
executed blocks and Kernel#caller for identifying them:

def do_once(&block)
executed_flag_name = “__#{caller[0].gsub(/\W/, “_”)}_executed”
if (eval(executed_flag_name, block) rescue nil) # works only with
non-scoped “for” loops
return
else
eval("#{executed_flag_name} = true", block)
yield
end
end


#2

Hi,

At Tue, 21 Oct 2008 19:07:46 +0900,
Evgeniy D. wrote in [ruby-talk:318215]:

rows = [“row1”, “row2”]

rows.each do |row|
if (first=true)…false and first


#3

2008/10/21 Nobuyoshi N. removed_email_address@domain.invalid:

At Tue, 21 Oct 2008 19:07:46 +0900,
Evgeniy D. wrote in [ruby-talk:318215]:

rows = [“row1”, “row2”]

rows.each do |row|
if (first=true)…false and first

Amazing!

write(header) # this block gets executed only once for whole loop
end

Here’s what I’d probably do

unless rows.empty?
write header

rows.each do |rw|
write row
end
end

Or

rows.each_with_index |row, index|
write header if index == 0
write row
end

Kind regards

robert


#4

You do not say if the “do once” code must rely on something obtained in
the loop. If you will excuse me for a simplistic question, if you are
doing something like writing a header, why not do it before you even
start the loop? I dislike checking for a conditional every time a loop
runs. It sucks up CPU time unnecessarily.


#5

2008/10/21 Robert K. removed_email_address@domain.invalid:

rows = [“row1”, “row2”]

rows.each do |row|
if (first=true)…false and first

Amazing!

This is awesome, but I don’t get all

if I write :
foo = (first=true)…false

I’ve got a 'bad value for Range", but it works in a condition for if.

first is a local variable the first time in the loop but not after, I
don’t understand why (the assignment first = true is not executed
each time ?).

very cute but puzzling.

– Jean-François.


#6

On Tue, Oct 21, 2008 at 9:05 AM, Lloyd L. removed_email_address@domain.invalid
wrote:

You do not say if the “do once” code must rely on something obtained in
the loop. If you will excuse me for a simplistic question, if you are
doing something like writing a header, why not do it before you even
start the loop? I dislike checking for a conditional every time a loop
runs. It sucks up CPU time unnecessarily.

Posted via http://www.ruby-forum.com/.

1.times {
puts ‘hi’
}


#7

The most embarrassing fact about Nobu’s solution is its all in Pickaxe
http://www.rubycentral.com/pickaxe/tut_expressions.html :slight_smile:

Exactly what happens is described in this quote: “You can use a Ruby
range
as a boolean expression. A range such as exp1…exp2 will evaluate
as false until exp1 becomes true. The range will then evaluate
as true until exp2 becomes true. Once this happens, the range resets,
ready to fire again”.

So exp1 (first=true) evaluates to true, then interpreter evaluates
boolean range
to true and waits until exp2 (false) becomes true which will never
happen,
but on all consequent runs “and first” will guard “if” body from
executing
(because exp1 is not executed anymore “first” gives you nil,
AFAIK what happens here is that “first” becomes “defined” name for the
interpreter
after first assignment but I can’t say I have good grasp on this
“scoping” feature).

The problem with Nobu’s solution obviously is inverse to mine (not
working with
“for” loops).

Re Robert K.: as I said before this example is contrived, think
about
cases where you don’t how many iteration there will be until you start
iterating.

Enumerable#each_with_index is cool, and you get it for free by defining
“each”
method on your class, but in my real-world case iterator isn’t called
each.

Re Jean-Francois Tran: seems like boolean range is completely
different beast from
Range object

Re Lloyd L.: I don’t remember when was the last time when I was
battling CPU
time issues (IO, DB - there are plenty of), moreover check for the
boolean flag
should be lightning fast (at least in ideal world :slight_smile: ).
So it just seems “nice and clean” to me to keep all stuff (table
generating in this case)
in one continuous block.

Re list. rb: now that’s refreshing :slight_smile:


#8

2008/10/21 Evgeniy D. removed_email_address@domain.invalid:

boolean range
to true and waits until exp2 (false) becomes true which will never happen,
but on all consequent runs “and first” will guard “if” body from executing

thanks for the explanations.

(because exp1 is not executed anymore “first” gives you nil,
AFAIK what happens here is that “first” becomes “defined” name for the
interpreter
after first assignment but I can’t say I have good grasp on this
“scoping” feature).

I guess it can be explained because at parse time, Ruby has seen
first assignment in the condition, and then considered ‘first’ as a
variable
even if the assignment is not executed.

it’s also in the Pickaxe :slight_smile:

http://www.rubycentral.com/pickaxe/language.html
chapter : Variable/Method Ambiguity

– Jean-François.