Newbie proc question

Can anyone help reduce my confusion? I think I understand the “how” of
proc blocks, but I still don’t get the “why,” particularly with a
dynamically passed block of code, like in the following sample:

def dummyMethod(&dynamicBlock)
dynamicBlock.call
end

dummyMethod {
puts 'This is line 1 of custom block code’
puts ‘This is line 2 of custom block code’
}

From what I’ve read, the proc block feature isn’t found in many
languages, and makes Ruby (and others like Lisp) much more flexible
and powerful. However, I don’t quite grasp why. Is the benefit that
you don’t need to modify “dummyMethod” at all, but rather just modify
the code within the block? And if this is the case, why is that
better? After all, if you have to make code changes, you still have to
change it somewhere, regardless of whether you’re changing it in
"dummyMethod" or in the code block. I don’t see the benefit of passing
blocks of code around instead of just including that code in the
method you’re calling.
I’m coming at this from a Visual Basic background, so I’m sure I’m a
bit like a Neanderthal being shown a power drill and wondering why
it’s any better than my rock tool. I get the feeling that proc blocks
can do great things, but I just don’t see why. And is there any
benefit to passing a dynamic block as shown above as opposed to
creating a new Proc object as shown here?

def dummyMethod(passedProcBlock)
passedProcBlock.call
end

newProcBlock = Proc.new {
puts 'This is line 1 of custom block code’
puts ‘This is line 2 of custom block code’
}

dummyMethod (newProcBlock)

Also, on a completely unrelated note, does anyone know how can I
change my Google Groups email display address to include the words
"REMOVE4SPAM" or some similar word? I tried changing it but Google
sends an email to the address to verify the change.
Thanks for everyone’s help! It’s very exciting being part of this
community, which seems to be on the cutting edge of the programming
future.

Can anyone help reduce my confusion?

···

----- Original Message -----
From: “James Toomey” jamesvtoomey@yahoo.com


Well, as I’m sure you have guessed, your examples weren’t really great uses
of blocks/procs.

So what’s the point of a proc? Well, it’s a little function you can pass
around. There are many times when you might want to do this. Basically,
it’s another level of abstraction. Let’s look at some low-level
abstractions and work our way up.

Let’s say you were writing a program where you wanted to say ‘hello’ three
times in a row. You might do something like:

puts 'hello’
puts 'hello’
puts ‘hello’

(We could have done a loop or something, but this is good enough for now.)
But what if I wanted to do the same thing from another spot in the code? I
could just copy and paste, but copy and paste is BAD. (Cut and paste is
fine… just no copying.) No, the thing to do is to group this code
together in a method:

def threeHellos
puts 'hello’
puts 'hello’
puts 'hello’
end

Now I can call this from any number of places in my code, no problem. I
don’t want duplicate code running around.

Now what if I wanted to say ‘goodbye’ three times in other places in my
code? I could define a new method threeGoodbyes', but it would share a great deal in common withthreeHellos’. I should refactor:

def sayItThreeTimes phrase
puts phrase
puts phrase
puts phrase
end

def threeHellos
sayItThreeTimes 'hello’
end

def threeGoodbyes
sayItThreeTimes 'goodbye’
end

Excellent. But what if, later on, I want to do something else three times?
Like get a string from user input and echo it?

def threeEchos
puts gets
puts gets
puts gets
end

It certainly has something in common with `sayItThreeTimes’, but how do we
factor it out? We use procs. After some more refactoring:

def doItThreeTimes aProc
aProc.call
aProc.call
aProc.call
end

def threeEchos
echoProc = proc {puts gets}
doItThreeTimes echoProc
end

def sayItThreeTimes phrase
sayItProc = proc {puts phrase}
doItThreeTimes sayItProc
end

See? Now we are passing in the proc as a normal parameter. Ruby has a
special way to pass in one proc per method call, though, using `&’:

def doItThreeTimes (&aProc)
aProc.call
aProc.call
aProc.call
end

def threeEchos
echoProc = proc {puts gets}
doItThreeTimes (&echoProc)
end

def sayItThreeTimes phrase
sayItProc = proc {puts phrase}
doItThreeTimes (&sayItProc)
end

Ruby also has a way to pass that proc in using a block, like this:

def threeEchos
doItThreeTimes {puts gets}
end

def sayItThreeTimes phrase
doItThreeTimes {puts phrase}
end

It means the same thing; it’s just that we don’t have to give it a name.
Similarly, if we want, we don’t have to give it a name in `doItThreeTimes’,
either:

def doItThreeTimes
yield
yield
yield
end

This also means the same thing: just call the special proc we passed in.

Of course, this was a silly example; we don’t need `doItThreeTimes’ when we
have this:

3.times { … }

n.times' takes a block and calls itn’ times.

So that’s one common use of blocks: iterators. `each’ is another popular
method which takes a block. I assume you are familiar with it?

Blocks are also useful when you have something you want done before and
after some code is called. Let’s say you were writing a profiler. To find
out how long a method call takes, you must find out the time before you call
the method, then the time after it is done, and subtract them:

startTime = Time.now

Put your code to profile here.

callTime = Time.now - startTime

Maybe you do this often, and you find yourself copying and pasting…
nonono! You can use blocks:

def profile
startTime = Time.now
yield # Call the code to be profiled.
Time.now - startTime
end

profile {12345**12345}

You can use this for logging, database transactions… This is often used
for file IO, since you want to open a file, do some stuff to it, then close
it at the end. If you use a block, you don’t have to bother with closing
it – Ruby will do it for you.

So does that make a little more sense?

Chris

In article 8fd3ee12.0304161737.32de03da@posting.google.com,

Can anyone help reduce my confusion? I think I understand the “how” of
proc blocks, but I still don’t get the “why,” particularly with a
dynamically passed block of code, like in the following sample:

def dummyMethod(&dynamicBlock)
dynamicBlock.call
end

dummyMethod {
puts ‘This is line 1 of custom block code’
puts ‘This is line 2 of custom block code’
}

From what I’ve read, the proc block feature isn’t found in many
languages, and makes Ruby (and others like Lisp) much more flexible
and powerful. However, I don’t quite grasp why. Is the benefit that
you don’t need to modify “dummyMethod” at all, but rather just modify
the code within the block?

No, that wouldn’t be much benefit.

And if this is the case, why is that
better? After all, if you have to make code changes, you still have to
change it somewhere, regardless of whether you’re changing it in
“dummyMethod” or in the code block.

Right.

I don’t see the benefit of passing
blocks of code around instead of just including that code in the
method you’re calling.
I’m coming at this from a Visual Basic background, so I’m sure I’m a
bit like a Neanderthal being shown a power drill and wondering why
it’s any better than my rock tool.

:wink:

I get the feeling that proc blocks
can do great things, but I just don’t see why.

Yes, you can do great things with them. Maybe a real world example is in
order.

I’ve created a hardware simulator using Ruby (RHDL) and there is a step
method that steps to the next simulation ‘time’ (think of it kind of like
using ‘step’ in a debugger to step to the next line in a program).

At first my step method didn’t take any arguments, but then I got the idea
that a user might want to display some information or perhaps change some
input(s) at each time step, so I made it so that step could take a block
and then remember that block until another block is given (saves a lot
typing for the user).

Without going into a lot of details, here’s how it works in practice:

#given some setup of signals: clk, rst, output:
step { clk = clk.inv #invert clk signal
#display signal values:
puts “clk=#{clk}, rst=#{rst}, output=#{output}”
}

So I guess the main point here is that the user of my API can add their
own code to specify what should be done from one step to another. The
user could put anything between the '{}'s. It essentially means that my
program becomes more flexible because I’ve allowed users to pass in their
own code.

Of course, this isn’t the only advantage of blocks. Probably the biggest
use is in iterators (like Array#each) - but the advantage is similar: it
allows the user of the iterator to specify some code that gets run at each
step of the iteration.

So to summerize: A big reason to allow a method to take a block is to
allow users of your code to pass in code. This makes your code more
flexible (usable in a greater number of situations) because when you allow
blocks you’re essentially saying that you are not trying to foresee every
possible way that your code should be used, so you’re allowing the user
of your code to insert code of their own to do what they need to get done.

Make sense?

This probably isn’t the only rationale for using blocks. I’m sure others
will provide other reasons.

The other thing to add here is that Ruby’s block mechanism is quite
elegant and unique - it essentially allows you to create domain specific
languages that look syntactically very natural. (RHDL is an example of
this)

Phil

···

James Toomey jamesvtoomey@yahoo.com wrote:

“James Toomey” jamesvtoomey@yahoo.com schrieb im Newsbeitrag
news:8fd3ee12.0304161737.32de03da@posting.google.com

Can anyone help reduce my confusion? I think I understand the “how” of
proc blocks, but I still don’t get the “why,” particularly with a
dynamically passed block of code, like in the following sample:

def dummyMethod(&dynamicBlock)
dynamicBlock.call
end

dummyMethod {
puts ‘This is line 1 of custom block code’
puts ‘This is line 2 of custom block code’
}

From what I’ve read, the proc block feature isn’t found in many
languages, and makes Ruby (and others like Lisp) much more flexible
and powerful. However, I don’t quite grasp why. Is the benefit that
you don’t need to modify “dummyMethod” at all, but rather just modify
the code within the block?

Exactly.

And if this is the case, why is that
better? After all, if you have to make code changes, you still have to
change it somewhere, regardless of whether you’re changing it in
“dummyMethod” or in the code block. I don’t see the benefit of passing
blocks of code around instead of just including that code in the
method you’re calling.

The benfit is increased modularity. For example, the ubiquituous method
“each” which typically is used to iterate through some kind of collection
deals with the iteration logic (the collection can be an array, a hash, a
set a tree - whatever) while blocks cover the treatment of iterated
elements. Without this separation you would

a) have to write a lot of methods containing the iteration and doing
different things to the elements

b) have to introduce a new method for new element treatment which is
especially awful if you’re not the creator of the class at hand (i.e.
you’re using a module from someone else)

I’m coming at this from a Visual Basic background, so I’m sure I’m a
bit like a Neanderthal being shown a power drill and wondering why
it’s any better than my rock tool. I get the feeling that proc blocks
can do great things, but I just don’t see why. And is there any
benefit to passing a dynamic block as shown above as opposed to
creating a new Proc object as shown here?

Proc objects can be stored and used later. Choose which ever is better
suited under certain conditions.

Thanks for everyone’s help! It’s very exciting being part of this
community, which seems to be on the cutting edge of the programming
future.

:slight_smile: Don’t let yourself be swept away too easily. Ruby is indeed great,
but there are other tools more approriate under certain circumstances.

Regards

robert

The other thing to add here is that Ruby’s block mechanism is quite
elegant and unique - it essentially allows you to create domain specific

I would not call it unique – as far as I understand, it came from Smaltalk,
where this technique is use quite extensively. Another block usage worth
mentioning is that the passed code may be executed in a controlled
enfironment. Say, before executing the code some resources may be allocated
(like, for example, locks) and released after the code is finished. It can
be arranged so that deallocation takes place even if the code raises
exception:

def method_accepting_block
obtain_lock
begin
yield if block_given?
ensure
release_lock
end
end

(or
def method_accepting_block(&block)
obtain_lock
begin
block.call unless block.nil?
ensure
release_lock
end
end
)

A great example of this approach is method File.open(). If a block is given,
File.open opens the file, executes the block making the file handle
available to it, and closes the file when the block terminates.

languages that look syntactically very natural. (RHDL is an example of
this)

Phil

Gennady.

···

----- Original Message -----
From: “Phil Tomson” ptkwt@shell1.aracnet.com
Newsgroups: comp.lang.ruby
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Wednesday, April 16, 2003 11:59 PM
Subject: Re: Newbie proc question