# Why does this use a block

**URL:** <https://rubytalk.org/t/why-does-this-use-a-block/41308>\
**Category:** ruby-talk\
**Created:** [11 October 2007 07:12 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308 "2007-10-11T07:12:04Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![Anonymous1](https://avatars.discourse-cdn.com/v4/letter/a/77aa72/32.png) [@Anonymous1](https://rubytalk.org/u/Anonymous1)\
**Post date:** [11 October 2007 07:12 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/1 "2007-10-11T07:12:04Z")

</div>

So I'm new to Ruby and I'm trying to use OptionParser to parse in some  
command line arguments. I looked at some documentation on OptionParser and  
there is something that's confusing me to no end. In all the examples a  
block is being passed in to the constructor of the OptionParser object. The  
constructor simply makes a yield call, passing self as an argument.

What is the point of this? Can we not convert

opts = OptionParser.new() {|opts| body}

To

opts = OptionParser.new()  
body

? This seems more natural to me. But the former seems like a common Ruby  
idiom so I'm wondering what I am missing.

Thanks,

Jaimrk

---

<div class="post-metadata">

**Author:** ![Eric\_Hodel1](https://avatars.discourse-cdn.com/v4/letter/e/a9adbd/32.png) [@Eric\_Hodel1](https://rubytalk.org/u/Eric_Hodel1)\
**Post date:** [11 October 2007 08:19 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/2 "2007-10-11T08:19:39Z")

</div>

It works both ways. Blocks are pretty, so people use them.

> **···**
>
> On Oct 11, 2007, at 24:12 , Anonymous wrote:
> 
> > So I'm new to Ruby and I'm trying to use OptionParser to parse in some  
> > command line arguments. I looked at some documentation on OptionParser and there is something that's confusing me to no end. In all the examples a block is being passed in to the constructor of the OptionParser object. The constructor simply makes a yield call, passing self as an argument.
> > 
> > What is the point of this? Can we not convert
> > 
> > opts = OptionParser.new() {|opts| body}
> > 
> > To
> > 
> > opts = OptionParser.new()  
> > body
> > 
> > ? This seems more natural to me. But the former seems like a common Ruby idiom so I'm wondering what I am missing.
> 
> --  
> Poor workers blame their tools. Good workers build better tools. The  
> best workers get their tools to do the work for them. -- Syndicate Wars

---

<div class="post-metadata">

**Author:** ![Erik\_Veenstra1](https://avatars.discourse-cdn.com/v4/letter/e/f04885/32.png) [@Erik\_Veenstra1](https://rubytalk.org/u/Erik_Veenstra1)\
**Post date:** [11 October 2007 09:27 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/3 "2007-10-11T09:27:31Z")

</div>

About using blocks in constructors in general...

(Although "initialize" is an initializer and not a constructor.  
It only takes care of one part of the construction.)

"initialize" should take care of the initialization of the  
object: Setting instance variables and checking whether the  
instance variables are set correctly. It's the latter which is  
important.

Setting instance variables is traditionally done in two ways: a  
list of arguments and a hash of options. (Or a combination of  
them.) You might want to call them "arguments" and "named  
arguments".

The list:

def initialize(first\_name, last\_name)  
&nbsp;&nbsp;&nbsp;@first\_name = first\_name.to\_s  
&nbsp;&nbsp;&nbsp;@last\_name = last\_name.to\_s

&nbsp;&nbsp;&nbsp;raise ArgumentError, "first name isn't set" unless @first\_name  
&nbsp;&nbsp;&nbsp;raise ArgumentError, "last name isn't set" unless @last\_name  
end

The hash:

def initialize(options={})  
&nbsp;&nbsp;&nbsp;@case\_sensitive = options[:case\_sensitive] || true  
&nbsp;&nbsp;&nbsp;@direction = options[:direction] || :forward

&nbsp;&nbsp;&nbsp;raise ArgumentError, "" unless @first\_name  
end

In Java, you'll often see a third way (Java style, Ruby code):

attr\_writer :first\_name  
attr\_writer :last\_name

def initialize  
end

something = Something.new  
something.first\_name = "Erik"  
something.last\_name = "Veenstra"

Personally, I think this is conceptually unacceptable: There's  
no way for the constructor to check whether the instance  
variables are set, or whether they are set correctly.

This can be overcome by calling the initializer with a block:

attr\_writer :first\_name  
attr\_writer :last\_name

def initialize(&block)  
&nbsp;&nbsp;&nbsp;block.call(self)

&nbsp;&nbsp;&nbsp;raise ArgumentError, "first name isn't set" unless @first\_name  
&nbsp;&nbsp;&nbsp;raise ArgumentError, "last name isn't set" unless @last\_name  
end

Which is called like this:

Something.new do |something|  
&nbsp;&nbsp;&nbsp;something.first\_name = "Erik"  
&nbsp;&nbsp;&nbsp;something.last\_name = "Veenstra"  
end

Personally, I always try to freeze the object once it is  
created: (This has advantages beyond the scope of this writing.)

attr\_writer :first\_name  
attr\_writer :last\_name

def initialize(&block)  
&nbsp;&nbsp;&nbsp;block.call(self)

&nbsp;&nbsp;&nbsp;raise ArgumentError, "first name isn't set" unless @first\_name  
&nbsp;&nbsp;&nbsp;raise ArgumentError, "last name isn't set" unless @last\_name

&nbsp;&nbsp;&nbsp;freeze  
end

There's some more advantages. For example, the object can often  
be collected earlier. Consider this example, in the main of the  
application:

direction = :forward

EV::CommandLine.new do |cl|  
&nbsp;&nbsp;&nbsp;cl.option("-r", "--reverse") {direction = :backward}  
end.parse(ARGV)

...instead of...

direction = :forward  
cl = EV::CommandLine.new  
cl.option("-r", "--reverse") {direction = :backward}  
cl.parse(ARGV)

When will cl be collected, in the second piece of code? Never?

It's just my opinion. Feel free to ignore me...

gegroet,  
Erik V. - [http://www.erikveen.dds.nl/](http://www.erikveen.dds.nl/)

---

<div class="post-metadata">

**Author:** ![Florian\_Frank2](https://avatars.discourse-cdn.com/v4/letter/f/a587f6/32.png) [@Florian\_Frank2](https://rubytalk.org/u/Florian_Frank2)\
**Post date:** [11 October 2007 09:34 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/4 "2007-10-11T09:34:21Z")

</div>

Anonymous wrote:

> So I'm new to Ruby and I'm trying to use OptionParser to parse in some  
> command line arguments. I looked at some documentation on OptionParser and  
> there is something that's confusing me to no end. In all the examples a  
> block is being passed in to the constructor of the OptionParser object. The  
> constructor simply makes a yield call, passing self as an argument.
> 
> What is the point of this? Can we not convert
> 
> opts = OptionParser.new() {|opts| body}
> 
> To
> 
> opts = OptionParser.new()  
> body
> 
> ? This seems more natural to me. But the former seems like a common Ruby  
> idiom so I'm wondering what I am missing.  
> &nbsp;&nbsp;

You might want to use the shortcut

option\_parser = OptionParser.new do |o|  
&nbsp;&nbsp;o.foo = "foo"  
&nbsp;&nbsp;o.bar = "bar"  
&nbsp;&nbsp;...  
end

during initialization of the object instead of using the long name, that  
will be used later in the program after you forgot, what "o" meant.

I don't know if this is the case with OptionParser, but many methods  
also want to do some housekeeping after the execution of the block, for  
example, open(...) do |f| ... end closes the opened file. A constructor  
might want to check his configuration (given in the block) and raise an  
exception, if errors were found. This is better than creating a wrongly  
configured object, that only will throw an exception later in the program.

> **···**
>
> --  
> Florian Frank

---

<div class="post-metadata">

**Author:** ![Todd\_Benson](https://avatars.discourse-cdn.com/v4/letter/t/34f0e0/32.png) [@Todd\_Benson](https://rubytalk.org/u/Todd_Benson)\
**Post date:** [11 October 2007 10:43 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/5 "2007-10-11T10:43:41Z")

</div>

You are asking a bunch of questions here, but I'll try my hand at one of them.

yield self

It pretty much does exactly what the statement says it does. Why  
would you do this upon initializing an object? I suppose, because you  
might want something else to accomplish something during  
initialization.

Blocks also give you control of scope and give the programmer a sense  
of finalization. File#open for example.

Todd

> **···**
>
> On 10/11/07, Anonymous \<jaimrk@aol.com\> wrote:
> 
> > So I'm new to Ruby and I'm trying to use OptionParser to parse in some  
> > command line arguments. I looked at some documentation on OptionParser and  
> > there is something that's confusing me to no end. In all the examples a  
> > block is being passed in to the constructor of the OptionParser object. The  
> > constructor simply makes a yield call, passing self as an argument.
> > 
> > What is the point of this? Can we not convert
> > 
> > opts = OptionParser.new() {|opts| body}
> > 
> > To
> > 
> > opts = OptionParser.new()  
> > body
> > 
> > ? This seems more natural to me. But the former seems like a common Ruby  
> > idiom so I'm wondering what I am missing.
> > 
> > Thanks,
> > 
> > Jaimrk

---

<div class="post-metadata">

**Author:** ![7stud1](https://avatars.discourse-cdn.com/v4/letter/7/59ef9b/32.png) [@7stud1](https://rubytalk.org/u/7stud1)\
**Post date:** [11 October 2007 13:16 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/6 "2007-10-11T13:16:31Z")

</div>

Anonymous wrote:

> So I'm new to Ruby and I'm trying to use OptionParser to parse in some  
> command line arguments.

In ruby, a lot of methods can be called with or without a block. When a  
method is called with a block, it may do some extra stuff. I think what  
the other posters are saying is that the initialize() method in  
OptionParser, which is called when you call new(), may be defined to do  
some extra things when it's called with a block.

Here's an example of a method doing some extra things when it's called  
with a block:

class Dog  
&nbsp;&nbsp;def age  
&nbsp;&nbsp;&nbsp;&nbsp;@age  
&nbsp;&nbsp;end

&nbsp;&nbsp;def age=(num)  
&nbsp;&nbsp;&nbsp;&nbsp;@age = num  
&nbsp;&nbsp;end

&nbsp;&nbsp;def initialize  
&nbsp;&nbsp;&nbsp;&nbsp;if block\_given?  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;yield self

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if @age == nil  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "You must set the dog's age."  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;elsif @age \> 20  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "Error. That dog is dead."  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;elsif @age \< 0  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;puts "Error. That dog isn't born yet."  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end

&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end  
end

d = Dog.new  
d.age = -3  
puts "That dog's age is #{d.age}."  
d.age = 22  
puts "That dog's age is #{d.age}."

d = Dog.new do |dog|  
&nbsp;&nbsp;dog.age = 22  
end

--output:--  
That dog's age is -3.  
That dog's age is 22.  
Error. That dog is dead.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Robert\_K1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/robert_k1/32/1830_2.png) [@Robert\_K1](https://rubytalk.org/u/Robert_K1)\
**Post date:** [11 October 2007 09:32 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/7 "2007-10-11T09:32:40Z")

</div>

There are in fact important differences to both approaches. First,  
OptionParser's #initialize is free to yield whatever it decides to the  
block. So you are not guaranteed to receive the new OptionParser  
instance. This is important to keep in mind because the  
implementation might change at a later point so the lib could yield a  
different instance which should, of course, support the documented  
interface.

Second, with the block form OptionParser#initialize is able to detect  
when the user initialization has finished and can do finalizing work.  
It could, for example, invoke #freeze to make sure the configuration  
is not changed any more. Or it can verify that client code properly  
initialized it (avoiding duplicate or ambiguous option settings for  
example).

An alternative that some may find nicer would implement OptionParser()  
(a method) in Kernel and have that receive the block.

Kind regards

robert

> **···**
>
> 2007/10/11, Eric Hodel \<drbrain@segment7.net\>:
> 
> > On Oct 11, 2007, at 24:12 , Anonymous wrote:  
> > \> So I'm new to Ruby and I'm trying to use OptionParser to parse in some  
> > \> command line arguments. I looked at some documentation on  
> > \> OptionParser and there is something that's confusing me to no end.  
> > \> In all the examples a block is being passed in to the constructor  
> > \> of the OptionParser object. The constructor simply makes a yield  
> > \> call, passing self as an argument.  
> > \>  
> > \> What is the point of this? Can we not convert  
> > \>  
> > \> opts = OptionParser.new() {|opts| body}  
> > \>  
> > \> To  
> > \>  
> > \> opts = OptionParser.new()  
> > \> body  
> > \>  
> > \> ? This seems more natural to me. But the former seems like a common  
> > \> Ruby idiom so I'm wondering what I am missing.
> > 
> > It works both ways. Blocks are pretty, so people use them.

---

<div class="post-metadata">

**Author:** ![Brian\_Adkins](https://avatars.discourse-cdn.com/v4/letter/b/3ab097/32.png) [@Brian\_Adkins](https://rubytalk.org/u/Brian_Adkins)\
**Post date:** [11 October 2007 16:20 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/8 "2007-10-11T16:20:04Z")

</div>

So, most of your objects are immutable?

> **···**
>
> On Oct 11, 5:27 am, Erik Veenstra \<erikv...@gmail.com\> wrote:
> 
> > Personally, I always try to freeze the object once it is  
> > created: (This has advantages beyond the scope of this writing.)

---

<div class="post-metadata">

**Author:** ![Rick\_DeNatale1](https://avatars.discourse-cdn.com/v4/letter/r/bbce88/32.png) [@Rick\_DeNatale1](https://rubytalk.org/u/Rick_DeNatale1)\
**Post date:** [11 October 2007 12:56 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/9 "2007-10-11T12:56:10Z")

</div>

I'm pretty sure that I've seen a variant on this in which initialize  
evaluates the block with instance\_eval rather than yield or call.  
This allows the block to invoke private methods during initialization.

IIRC the Ruby tk bindings so this.

> **···**
>
> On 10/11/07, Robert Klemme \<shortcutter@googlemail.com\> wrote:
> 
> > 2007/10/11, Eric Hodel \<drbrain@segment7.net\>:  
> > \> On Oct 11, 2007, at 24:12 , Anonymous wrote:  
> > \> \> So I'm new to Ruby and I'm trying to use OptionParser to parse in some  
> > \> \> command line arguments. I looked at some documentation on  
> > \> \> OptionParser and there is something that's confusing me to no end.  
> > \> \> In all the examples a block is being passed in to the constructor  
> > \> \> of the OptionParser object.
> 
> > \> It works both ways. Blocks are pretty, so people use them.
> > 
> > There are in fact important differences to both approaches. First,  
> > OptionParser's #initialize is free to yield whatever it decides to the  
> > block. So you are not guaranteed to receive the new OptionParser  
> > instance. This is important to keep in mind because the  
> > implementation might change at a later point so the lib could yield a  
> > different instance which should, of course, support the documented  
> > interface.
> > 
> > Second, with the block form OptionParser#initialize is able to detect  
> > when the user initialization has finished and can do finalizing work.  
> > It could, for example, invoke #freeze to make sure the configuration  
> > is not changed any more. Or it can verify that client code properly  
> > initialized it (avoiding duplicate or ambiguous option settings for  
> > example).
> 
> --  
> Rick DeNatale
> 
> My blog on Ruby  
> [http://talklikeaduck.denhaven2.com/](http://talklikeaduck.denhaven2.com/)

---

<div class="post-metadata">

**Author:** ![Erik\_Veenstra1](https://avatars.discourse-cdn.com/v4/letter/e/f04885/32.png) [@Erik\_Veenstra1](https://rubytalk.org/u/Erik_Veenstra1)\
**Post date:** [11 October 2007 19:33 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/10 "2007-10-11T19:33:46Z")

</div>

> So, most of your objects are immutable?

Yes. (If possible...)

Q: Why?

gegroet,  
Erik V. - [http://www.erikveen.dds.nl/](http://www.erikveen.dds.nl/)

> **···**
>
> A: [Functional Relational Programming: Out of the tar pit | Lambda the Ultimate](http://lambda-the-ultimate.org/node/1446)

---

<div class="post-metadata">

**Author:** ![Brian\_Adkins](https://avatars.discourse-cdn.com/v4/letter/b/3ab097/32.png) [@Brian\_Adkins](https://rubytalk.org/u/Brian_Adkins)\
**Post date:** [11 October 2007 20:40 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/11 "2007-10-11T20:40:07Z")

</div>

Have you thought of programming in Haskell? 😉

I'm familiar with some of the benefits of avoiding state with respect  
to functional programming languages, but to impose that strictly on  
Ruby seems to be working against the grain. I do code many functions  
(i.e. not associated with a meaningful instance) in a functional style  
w/o side effects, but when working with objects, having methods modify  
the state of objects seems to be very natural and productive in Ruby.

I'm curious though because of my recent research into Haskell, SML,  
etc.. Do you have an example of this style of programming (frozen  
objects) in Ruby that you feel is compelling?

Brian Adkins

> **···**
>
> On Oct 11, 3:33 pm, Erik Veenstra \<erikv...@gmail.com\> wrote:
> 
> > \> So, most of your objects are immutable?
> > 
> > Yes. (If possible...)
> > 
> > Q: Why?  
> > A:[Functional Relational Programming: Out of the tar pit | Lambda the Ultimate](http://lambda-the-ultimate.org/node/1446)
> 
> --  
> [http://www.lojic.com](http://www.lojic.com)
> 
> > **[Lojic Technologies Blog](https://blog.lojic.com//)**
> >
> > Lojic Technologies Blog

---

<div class="post-metadata">

**Author:** ![Robert\_K1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/robert_k1/32/1830_2.png) [@Robert\_K1](https://rubytalk.org/u/Robert_K1)\
**Post date:** [12 October 2007 06:40 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/12 "2007-10-12T06:40:17Z")

</div>

> \> \> So, most of your objects are immutable?  
> \>  
> \> Yes. (If possible...)  
> \>  
> \> Q: Why?  
> \> A:[http://lambda-the-ultimate.org/node/1446](http://lambda-the-ultimate.org/node/1446)
> 
> Have you thought of programming in Haskell? 😉

🙂

> I'm familiar with some of the benefits of avoiding state with respect  
> to functional programming languages, but to impose that strictly on  
> Ruby seems to be working against the grain. I do code many functions  
> (i.e. not associated with a meaningful instance) in a functional style  
> w/o side effects, but when working with objects, having methods modify  
> the state of objects seems to be very natural and productive in Ruby.

Actually programming completely without side effects defies the core  
of the OO paradigm. Objects simply do not make much sense if methods  
cannot produce side effects.

> I'm curious though because of my recent research into Haskell, SML,  
> etc.. Do you have an example of this style of programming (frozen  
> objects) in Ruby that you feel is compelling?

Look at all the math in Ruby - I believe it makes very much sense the  
way it is done today. But any collection type would be rather  
inefficient when you always had to create a new object for every  
change - at least in the Ruby world. I believe that some functional  
language runtime systems are pretty smart and can optimize this to a  
certain extend.

It's all about balance. Use side effects when appropriate, use  
immutables when appropriate.

Kind regards

robert

> **···**
>
> 2007/10/11, Brian Adkins \<lojicdotcom@gmail.com\>:
> 
> > On Oct 11, 3:33 pm, Erik Veenstra \<erikv...@gmail.com\> wrote:

---

<div class="post-metadata">

**Author:** ![Rick\_DeNatale1](https://avatars.discourse-cdn.com/v4/letter/r/bbce88/32.png) [@Rick\_DeNatale1](https://rubytalk.org/u/Rick_DeNatale1)\
**Post date:** [12 October 2007 22:16 UTC](https://rubytalk.org/t/why-does-this-use-a-block/41308/13 "2007-10-12T22:16:27Z")

</div>

I'd agree. Multi-paradigm programming is one thing, but this seems  
more like counter paradigm programming.

Sort of like speaking English fluent with grammar French.

> **···**
>
> On 10/12/07, Robert Klemme \<shortcutter@googlemail.com\> wrote:
> 
> > Actually programming completely without side effects defies the core  
> > of the OO paradigm. Objects simply do not make much sense if methods  
> > cannot produce side effects.
> 
> --  
> Rick DeNatale
> 
> My blog on Ruby  
> [http://talklikeaduck.denhaven2.com/](http://talklikeaduck.denhaven2.com/)
