Created
November 9, 2011 14:47
-
-
Save zonuexe/1351636 to your computer and use it in GitHub Desktop.
初心者向けのプログラミングの練習問題みたいなのをRubyで
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# C言語と同じふうにやると、たぶんこんな感じに | |
i = 0 | |
while(i < 10) | |
j = 0 | |
while(j <= i) | |
print "*" | |
j += 1 | |
end | |
print "\n" | |
i += 1 | |
end | |
# ここまで | |
# 空行 | |
puts() | |
(1..10).map{|i| | |
AstLine.new(i) | |
}.each{|a| | |
a.print | |
} | |
# (1..10) : 1〜10までの数字が並んだモノ(Rangeオブジェクト) | |
# ***.map{|i| : 「何か」が並んだモノに対して、そのそれぞれを参照して並べて返す | |
# 今回は 1,2,3,4,5,6,7,8,9,10 と並んでる。その中身は i に代入。 | |
# AstLine.new(i) : AstLineクラスの(インスタンス)オブジェクトを作る。 | |
# ***.each{|a| : map は「何か」を並べて返してくれるので、そのそれぞれを参照して処理を実行する。 | |
# a にはその並べられた中身(この場合はAstLineオブジェクト)が入ってる。 | |
# a.print : Astrineオブジェクトのprintメソッドを呼び出す(実行する[させる])。 | |
# BEGIN{} で括った中身はスクリプトの最初に実行される | |
BEGIN{ | |
class AstLine | |
def initialize(n) | |
@n = n | |
end | |
def str | |
@str ||= "*" * @n | |
end | |
def to_s | |
self.str | |
end | |
def inspect | |
"#<Astline:n=#{@n}@\"#{self.str}\">" | |
end | |
def print | |
puts self.str | |
end | |
end | |
# AstLineクラスは「*」を一行に一定の数並べることを目的とする | |
# インスタンスは、表示される一行を表現する | |
# インスタンスは変数 @n を持ち、一行に表示する「*」の個数を表す | |
# | |
# インスタンスメソッド str は表示する「*」を @n の個数並べた文字列を作成して、返す | |
# インスタンスメソッド to_s は表示する文字列を返す。内部で str を利用する | |
# インスタンスメソッド print は「*」を @n の個数並べた文字列を表示する。内部で str を利用する | |
# インスタンスメソッド inspect はデバッグ用の出力 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment