A Few Things to Try on 5. More About Methods

 Rubyでプログラミング勉強中(参照)。

 今日は、Chapter 5. More About Methods(参照)でMethodの基礎を学ぶ。ObjectとMethodについての理解がちょっとだけ深まった。以下のくだりが個人的には非常に分かりやすかったかな。

So far we’ve seen a number of different methods, puts and gets and so on (Pop Quiz: List all of the methods we have seen so far! There are ten of them; the answer is below.), but we haven’t really talked about what methods are. We know what they do, but we don’t know what they are.

But really, that is what they are: things that do stuff. If objects (like strings, integers, and floats) are the nouns in the Ruby language, then methods are like the verbs. And, just like in English, you can’t have a verb without a noun to do the verb. For example, ticking isn’t something that just happens; a clock (or a watch or something) has to do it. In English we would say, “The clock ticks.” In Ruby we would say clock.tick (assuming that clock was a Ruby object, of course). Programmers might say we were “calling clock’s tick method,” or that we “called tick on clock.”

5. More About Methods

 というわけで、以下、このChapterの練習問題記録。

A Few Things to Try on 5. More About Methods

一問目

• Write an Angry Boss program. It should rudely ask what you want. Whatever you answer, the Angry Boss should yell it back to you, and then fire you. For example, if you type in I want a raise., it should yell back WHADDAYA MEAN “I WANT A RAISE.”?!? YOU’RE FIRED!!

5. More About Methods

これは、簡単やね。別にupcase methodを使う必要もないのだけど、ObjectとMethodの理解を深めるために蛇足と知りつつ、使ってみた。

puts 'I said..'
iSay = gets.chomp
puts 'Whaddaya mean '.upcase + '"' + iSay.upcase + '"?!? ' + 'You\'re fired!!'.upcase

二問目

• So here’s something for you to do in order to play around more with center, ljust, and rjust: Write a program which will display a Table of Contents so that it looks like this:

5. More About Methods

Table of Contents
Chapter 1:  Numbers                        page 1
Chapter 2:  Letters                       page 72
Chapter 3:  Variables                    page 118

これも、このChapterをきちんと読めば楽勝。

lineWidth = 50
puts ''
puts 'Table of Contents'.center (lineWidth)
puts ''
puts 'Chapter 1:  Numbers  '.ljust (lineWidth/2) + '  page 1'.rjust (lineWidth/2)
puts 'Chapter 2:  Letters  '.ljust (lineWidth/2) + ' page 72'.rjust (lineWidth/2)
puts 'Chapter 3:  Variables'.ljust (lineWidth/2) + 'page 181'.rjust (lineWidth/2)

雑感

 このChapter 5. More About Methodsまでで、基本の基本の基本部分を終えたという感じ。次回は、Flow Control(制御構造)。if文とかwhile文が登場して、さらに楽しくなっていきそう。

See also

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.