Tim Toady

Something I have tried to shield you from, but that you will surely run into soon, is the concept of TMTOWTDI (pronounced Tim Toady, I think): There’s More Than One Way To Do It.

Now some will tell you what a wonderful thing TMTOWTDI is, while others feel quite differently. I think it’s pretty cool, because having more than one way to do something feels more expressive. Nonetheless, I think it’s a terrible way to teach someone how to program. (Learning one way to do something is challenging and confusing enough.)

However, now that you are moving beyond this book, you’ll be seeing much more diverse code. For example, I can think of at least five other ways to make a string (aside from surrounding some text in single quotes), and each one works slightly differently. I showed you only the simplest of the six.

And when we talked about branching, I showed you if, but I didn’t show you unless. I’ll let you figure that one out in irb.

Another nice little shortcut you can use with if, unless, and while is the cute one-line version:

# These words are from a program I wrote to generate
# English-like babble. Cool, huh?
puts ​'combergearl thememberate'​ ​if​ 5 == 2**2 + 1**1
puts ​'supposine follutify'​ ​unless​ ​'Chris'​.length == 5
combergearl thememberate

And finally, there is another way of writing methods that take blocks (not procs). We saw the thing where we grabbed the block and turned it into a proc using the &block trick in our parameter list when we define the method. Then, to call the block, we just use block.call. Well, there’s a shorter way (though I personally find it more confusing). Instead of this…

def​ do_it_twice(&block)
block.call
block.call
end
do_it_twice ​do
puts ​'murditivent flavitemphan siresent litics'
end
murditivent flavitemphan siresent litics
murditivent flavitemphan siresent litics

you do this…

def​ do_it_twice
yield
yield
end
do_it_twice ​do
puts ​'buritiate mustripe lablic acticise'
end
buritiate mustripe lablic acticise
buritiate mustripe lablic acticise

I don’t know…what do you think? Maybe it’s just me, but yield?! If it was something like call_the_hidden_block, that would make a lot more sense to me. A lot of people say yield makes sense to them. But I guess that’s what TMTOWTDI is all about: they do it their way, and I’ll do it my way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.192.247